Given an array, reverse every group of consecutive m elements in a given subarray of it.

For example,

Consider the below array.
 
A[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 },
m = 3
 
Then for subarray [i, j], where i and j is
 
 
Input:  i = 1, j = 7 or 8
Output: [1, 4, 3, 2, 7, 6, 5, 8, 9, 10]
 
 
Input:  i = 1, j = 9
Output: [1, 4, 3, 2, 7, 6, 5, 10, 9, 8]
 
 
Input:  i = 3, j = 5
Output: [1, 2, 3, 6, 5, 4, 7, 8, 9, 10]
 
 
Input:  i = 3, j = 4
Output: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Practice this problem

The solution can be implemented as follows in C, Java, and Python:

C


Download  Run Code

Output:

1 4 3 2 7 6 5 8 9 10

Java


Download  Run Code

Output:

[1, 4, 3, 2, 7, 6, 5, 8, 9, 10]

Python


Download  Run Code

Output:

[1, 4, 3, 2, 7, 6, 5, 8, 9, 10]

The time complexity of the above solution is O(n), where n is the size of the input. Since we pass the subarray’s endpoints (we want to reverse) to the second reverse function, and the subarray size would be exactly m, its complexity would be O(m). Inside the main reverse function, there will be exactly n/m calls made to the second reverse function so that the overall time complexity will be m×(n/m) = O(n). The auxiliary space required by the program is O(n) for recursion (call stack).