Reverse an Array

Given an array, reverse it in place so the last element becomes the first, using only constant extra space.

EasyOptionalBasic Traversal
Solve This Problem

Video Solution

Video coming soon

We're producing a video walkthrough — check back soon.

Problem Overview

Given an array, reverse it in place so the last element becomes the first, using only constant extra space.

Why solve this?

The first in-place mutation problem in this course — the two-pointer swap introduced here reappears in every later partitioning and rotation problem.

Pattern Recognition

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.

Prerequisites

  • No prior lessons required — this is the starting point for in-place array manipulation.

Hints

  1. You don't need a second array — swap elements directly inside the given one.
  2. Keep one pointer at the start and one at the end, and walk them toward each other.
  3. Stop once the two pointers meet or cross.

Approach

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.

Code

Solution.java
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--;
        }
    }
}
Time: O(n)Space: O(1)

Related Problems

Back to Arrays