Swap Kth Elements
Given an array ‘ARR’ of size ‘N,’ swap the Kth element from beginning with the Kth element from the end.
For example:
If ‘N’ = 5 and K = 2
[1, 2, 3, 4, 5]
Then the output will be [1, 4, 3, 2, 5].
Input format :
The first line of input contains an integer T denoting the number of test cases.
The first line of each test case contains two space-separated integers N, and K, where N is the number of elements of the array and K is the index.
The second line of each test case contains ‘N’ space-separated integers, denoting the array elements.
Output format :
For each test case, print the array after swapping the Kth element from the start and the Kth element from the end.
The output of each test case will be printed in a separate line.
Note:
You do not need to print anything; it has already been taken care of. Just implement the given function.
Constraints:
1 <= T <= 5
1 <= K < N <= 5000
Time Limit : 1 sec
CodingNinjas
author
2y
Step 1: Find the kth node from the start and the kth node from the end (n-k+1th node from start)
Step 2: Swap both the nodes
CodingNinjas
author
2y
Traverse till Kth index.
- Initialize two pointers, one from the beginning and on the other end of the array.
- Move the beginning pointer K times and simultaneously move the end pointer backward K times.
- Sw...read more
CodingNinjas
author
2y
Direct Swap
- We can directly swap the elements at the Kth position and (N - K)th position.
O(1)
Since we are not using any extra space.
Time Complexity: O(1)Explanation:...read moreAdd answer anonymously...
Top Indiamart Intermesh Associate Software Engineer interview questions & answers
Popular interview questions of Associate Software Engineer
Top HR questions asked in Indiamart Intermesh Associate Software Engineer
>
Indiamart Intermesh Associate Software Engineer Interview Questions
Stay ahead in your career. Get AmbitionBox app
Helping over 1 Crore job seekers every month in choosing their right fit company
65 L+
Reviews
4 L+
Interviews
4 Cr+
Salaries
1 Cr+
Users/Month
Contribute to help millions
Get AmbitionBox app