Algorithms and Data Structures · Junior · Question 41 of 75

How do you reverse an array in place with O(1) extra memory?

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.

Further reading

Problem with a question

Algorithms and Data Structures · Junior · question 41

Test yourself

Take the Algorithms and Data Structures · Junior quiz: questions and options are shuffled, and you get a review of your mistakes at the end.

Take this quiz