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 array

A[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 } and
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++

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


 
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).
 

Thanks for reading.




Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 





Leave a Reply

Notify of
avatar
Sort by:   newest | oldest | most voted
Anshul
Guest
Anshul

Good example of function overloading.

wpDiscuz