Skip to main content

Reverse array in groups

Problem​

Given an array arr[] of positive integers of size N. Reverse every sub-array group of size K.

Note: If at any instance, there are no more subarrays of size greater than or equal to K, then reverse the last subarray (irrespective of its size). You shouldn't return any array, modify the given array in-place.

Examples:​

Example 1:

Input:
N = 5, K = 3
arr[] = {1,2,3,4,5}
Output: 3 2 1 5 4
Explanation: First group consists of elements 1, 2, 3. Second group consists of 4,5.

Example 2:

Input:
N = 4, K = 3
arr[] = {5,6,8,9}
Output: 8 6 5 9

Your Task:​

You don't need to read input or print anything. The task is to complete the function reverseInGroups() which takes the array, N and K as input parameters and modifies the array in-place.

  • Expected Time Complexity: O(N)O(N)
  • Expected Auxiliary Space: O(1)O(1)

Constraints:​

  • 1≀N,K≀1071 ≀ N, K ≀ 10^7
  • 1≀A[i]≀10181 ≀ A[i] ≀ 10^{18}

Solution​

Python​

def reverseInGroups(self, arr, N, K):
i = 0
while(i<N):
left = i
right = min(i + K - 1, N - 1)
while (left < right):
arr[left], arr[right] = arr[right], arr[left]
left+= 1;
right-=1
i+= K

Java​

void reverseInGroups(ArrayList<Integer> arr, int n, int k) {
for (int i = 0; i < n; i += k) {
int left = i;
int right = Math.min(i + k - 1, n - 1);
while (left < right) {
int temp = arr.get(left);
arr.set(left, arr.get(right));
arr.set(right, temp);
left++;
right--;
}
}
}

C++​

void reverseInGroups(vector<long long>& arr, int n, int k){
for (int i = 0; i < n; i += k) {
int left = i;
int right = min(i + k - 1, n - 1);
while (left < right)
swap(arr[left++], arr[right--]);
}
}

C​

void reverse(int arr[], int n, int k) {
for (int i = 0; i < n; i += k) {
int left = i;
int right;
if(i+k-1<n-1)
right = i+k-1;
else
right = n-1;
while (left < right) {
int temp = arr[left];
arr[left] = arr[right];
arr[right] = temp;
left++;
right--;
}
}
}
  • Time Complexity: O(N)O(N)
  • Auxiliary Space: O(1)O(1)