Given an array, reverse it in place so the last element becomes the first, using only constant extra space.
Video coming soon
We're producing a video walkthrough — check back soon.
Given an array, reverse it in place so the last element becomes the first, using only constant extra space.
The first in-place mutation problem in this course — the two-pointer swap introduced here reappears in every later partitioning and rotation problem.
Any prompt asking you to rearrange an array in place with O(1) extra space, where elements only swap positions rather than change value, is a two-pointer traversal.
Place one pointer at the start and one at the end of the array. Swap the values they point to, then move the left pointer forward and the right pointer backward. Repeat until the pointers meet or cross — every pair has then been swapped exactly once, and the array is fully reversed. Each element is touched a constant number of times, so the whole pass is linear.
class Solution {
public void reverseArray(int[] nums) {
int left = 0, right = nums.length - 1;
while (left < right) {
int temp = nums[left];
nums[left] = nums[right];
nums[right] = temp;
left++;
right--;
}
}
}