→ "In place" and "don't create a second array" rule out copying
→ The first and last elements trade places, then the second and second-to-last: a symmetric job from both ends
These clues point to Two Pointers: Opposite Ends: Start one pointer at each end and move them towards each other, using a rule to decide which one moves.
Stuck? Take one hint at a time
Solution.java · starter
class Solution {
public void reverse(int[] nums) {
// swap from both ends towards the middle
}
}
Write your solution locally or in your editor for now. The in-browser runner (Java first, then Python, C++ and more) will run these tests right here.
Make a second array of the same length, fill it from the back of the original, then copy it back. Easy to get right, but it uses O(n) extra memory, which the problem forbids.
Approach 1
class Solution {
public void reverse(int[] nums) {
int n = nums.length;
int[] copy = new int[n];
for (int i = 0; i < n; i++) copy[i] = nums[n - 1 - i];
for (int i = 0; i < n; i++) nums[i] = copy[i];
}
}
Verdict: Correct, but breaks the O(1) space rule. Good as a first step to check your understanding.
2
Optimal: two pointers swapping inwards
Time O(n) Space O(1)
Put left at the start and right at the end. Swap the two elements, then move left one step right and right one step left. Every swap fixes two positions for good.
Stop when left >= right: if they meet at the same index (odd length), that middle element stays where it is.
Set left = 0, right = n - 1.
While left < right: swap nums[left] and nums[right], then left++, right--.