AlgoMaster Logo

Reverse an Array In Place

Last Updated: June 7, 2026

easy
3 min read

Understanding the Problem

Flip the order of the elements so the last one becomes first, the second-to-last becomes second, and so on. The phrase "in place" is the constraint that matters: you cannot build a fresh array and copy values into it. You must rearrange the existing array using only a constant amount of extra space.

A few cases keep the logic honest. An empty array reverses to an empty array. A single-element array stays the same because there is nothing to swap. Arrays with negative numbers reverse the same way as any other, since reversing cares about position, not value.

Key Constraints:

  • 0 <= nums.length <= 10^4 → The array can be empty. Your loop must handle a length of 0 without touching any elements, and it must finish quickly even at the upper size.
  • O(1) extra space → You cannot allocate a second array. The only storage you are allowed is a handful of variables, such as the two indices and one temporary value used during a swap.

Approach 1: Two Pointers

Intuition

Copying elements into a new array from back to front works, but it costs O(n) extra space for the second full-size array, which the constraint forbids.

Instead, swap pairs from the outside in. Place one pointer at the start and another at the end. The two values they point to need to trade places in the final result, so swap them. Then move the left pointer one step right and the right pointer one step left, and repeat. Each swap fixes two elements into their final positions at once, so the pointers only travel until they meet in the middle.

The only memory this needs is the two indices and one temporary variable used during each swap, which is O(1) extra space.

Algorithm

  1. Set left = 0 and right = nums.length - 1.
  2. While left < right, swap nums[left] and nums[right].
  3. After each swap, increment left and decrement right.
  4. Stop when the pointers meet or cross, then return nums.

Example Walkthrough

Input:

1Start: left = 0, right = 4. Swap nums[0] and nums[4].
0
left
1
1
2
2
3
3
4
4
5
right
1/4

Start with left = 0 and right = 4. The values there are 1 and 5, so swap them. The array becomes [5, 2, 3, 4, 1]. Move the pointers inward to left = 1 and right = 3. The values there are 2 and 4, so swap them. The array becomes [5, 4, 3, 2, 1]. Move inward again to left = 2 and right = 2. The pointers now point at the same middle element, so the condition left < right is false and the loop stops. The element at index 2 never needed to move because it sits exactly in the center.

0
5
1
4
2
3
3
2
4
1
result

Code