Saturday 3 February 2018

Reverse an array with space complexity of the solution should be O(1)

 Arrays & Strings

Problem:

           Reverse an array in-place i.e you cannot use any additional array or in other words, space complexity of the solution should be O(1)

Solution:

1) Use two variables (a,b) initialized with the first (0) and last index (n-1) respectively of the array of 'n' elements.
2) Swap the values at arr(a) and arr(b).
3) Increment a and decrement b.
4) Repeat step 2 till a and b intersects. 

 

No comments:

Post a Comment