# Reverse every consecutive m elements of the given subarray

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

For example, consider the array

A[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }
m = 3,

Then for subarray [i, j], where i and j is

i = 1, j = 7 or 8
Output: { 1, 4, 3, 2, 7, 6, 5, 8, 9, 10}

i = 1, j = 9
Output: { 1, 4, 3, 2, 7, 6, 5, 10, 9, 8}

i = 3, j = 5
Output: { 1, 2, 3, 6, 5, 4, 7, 8, 9, 10}

i = 3, j = 4
Output: { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}

## C

Output:

1 4 3 2 7 6 5 8 9 10

## Java

Output:

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

The time complexity of above solution is O(n). Since we are passing the end points of the subarray 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 second reverse function, so the overall time complexity will be m * (n/m) = O(n). Auxiliary space used by the program is O(1).

(1 votes, average: 5.00 out of 5)

Loading...

Thanks for reading.

Please use our online compiler to post code in comments. To contribute, get in touch with us.
Like us? Please spread the word and help us grow. Happy coding 🙂

### Leave a Reply

Subscribe
Notify of
Guest

Good example of function overloading.