Course contentsShow
← Computer Science
Lesson 253 of 2,8726. Arrays and Basic CollectionsFree lesson

Array Reversal In-Place

Reverse array element order using two-pointer technique without allocating additional space, achieving O(1) space complexity.

Array Reversal In-Place

What you'll learn: How to reverse an array's elements without using extra memory by swapping elements from opposite ends.

The Core Idea

Imagine you have a row of books on a shelf and want to reverse their order. Instead of getting a second shelf (extra memory), you can simply swap the first book with the last, the second with the second-to-last, and so on, working your way toward the middle. This is exactly how in-place array reversal works!

The Two-Pointer Technique

You use two "pointers" (really just index variables):

  • One starts at the beginning of the array (index 0)
  • One starts at the end (index length - 1)

At each step:

  1. Swap the elements at these two positions
  2. Move the left pointer one step right
  3. Move the right pointer one step left
  4. Stop when the pointers meet or cross

Why It Matters

This approach achieves O(1) space complexity—it uses only a constant amount of extra memory (just the two index variables and one temporary variable for swapping). You're modifying the original array directly rather than creating a new reversed copy.

For example, reversing [1, 2, 3, 4, 5]:

  • Swap 1 and 5 → [5, 2, 3, 4, 1]
  • Swap 2 and 4 → [5, 4, 3, 2, 1]
  • Middle element 3 stays (pointers met)

You iterate through roughly half the array, making this O(n) time complexity with minimal memory overhead.

Key Takeaway: In-place array reversal uses the two-pointer technique to swap elements from opposite ends, meeting in the middle, achieving O(1) space complexity without allocating additional memory.