Algorithms and Data Structures · Junior · Question 41 of 75
How do you reverse an array in place with O(1) extra memory?
- 1Copy elements into a new array from the end
- ✓Correct answer: Swap elements from both ends, moving toward the middle
- 3Push every element onto a stack and pop them back
Explanation
Two pointers i = 0 and j = n - 1 swap arr[i] and arr[j] and move toward each other until they meet. Copying or using a stack needs O(n) extra memory.