Swap Kth Elements

Easy
0/40
Average time to solve is 15m
profile
Contributed by
4 upvotes
Asked in companies
Livekeeping (An IndiaMART Company)Morgan StanleyAirtel

Problem statement

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].
Detailed explanation ( Input/output format, Notes, Images )
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
Sample Input 1 :
1
8 3
1 2 3 4 5 6 7 8
Sample Output 1 :
1 2 6 4 5 3 7 8

Explanation For Sample Input 1:

The Kth element from the beginning is 3 and from the end is 6.

Sample Input 2 :

1
5 2
1 2 3 4 5

Sample Output 2 :

1 4 3 2 5
Hint

Can we do it directly?

Approaches (2)
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.
  • Swap the elements that are being pointed by the begging pointer and the end pointer.
Time Complexity

O(N), where N is the size of the given array.

 

At worst, K can be equal to N, and then we have to traverse the array completely. Therefore, O(K + K) = O(N + N) = O(N).

Space Complexity

O(1)

 

Since we are not using any extra space.

Code Solution
(100% EXP penalty)
Swap Kth Elements
Full screen
Console