Swap kth elements

swap the kth number from the beginning and the end of the array

Example 1:

Input: 
N = 6, k = 2
Arr[] = {14, 48, 9, 17, 35, 1}
Output: 14, 35, 9, 17, 48, 1
Explanation: 48 and 35 are the 2nd element from beginning and end respectively

Example 2:

Input: 
N = 8, k = 4
Arr[] = {1,2,3,4,5,6,7,8,9,10}
Output: 1,2,3,7,5,6,4,8,9,10
Explanation: 4 and 7 will be swapped

 


method 1:

Java implementation:

class Codemummy {
    void swapKth(int arr[], int n, int k) {
       int temp= arr[k-1];
       arr[k-1]=arr[n-k];
       arr[n-k]=temp;
    }
}

 Time Complexity: O(1)
Auxiliary Space: O(1).





c++ implementation:

void swapKth(int arr[], int n, int k) {
   int temp= arr[k-1];
   arr[k-1]=arr[n-k];
   arr[n-k]=temp;
}

 Time Complexity: O(1)
Auxiliary Space: O(1).




python implementation:

def swapKth(arr, n, k):
    temp = arr[k-1]
    arr[k-1] = arr[n-k]
    arr[n-k] = temp

 Time Complexity: O(1)
Auxiliary Space: O(1).









No comments

darkmode