Reverse Array in Groups
Problem Statement
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).
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
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)
Expected Auxiliary Space : O(N)
Constraints :
1 <= N <= 107
1 <= A[i] <= 1018
Solutions
Java Solution
class Solution {
//Function to reverse every sub-array group of size k.
void reverseInGroups(ArrayList<Integer> arr, int n, int k) {
// code here
for (int i=0; i<n; i=i+k) {
int l = i;
if (n - l >= k) {
for (int j = i + k-1; j > l; j--, l++) {
int temp = arr.get(l);
arr.set(l, arr.get(j));
arr.set(j, temp);
}
} else {
for (int j = n-1; j > l; j--, l++) {
int temp = arr.get(l);
arr.set(l, arr.get(j));
arr.set(j, temp);
}
break;
}
}
}
}
0 Comments