Skip to content

Array Reversal

Reverse the order of elements in an array in-place using symmetric swaps.

Array reversal rearranges elements so that the first becomes the last, the second becomes the second last, and so on.

You use it as a basic primitive in many algorithms, including rotation, palindrome checks, and two-pointer techniques.

Problem

Given an array AA of length nn, transform it into:

A=[an1,an2,,a0] A' = [a_{n-1}, a_{n-2}, \dots, a_0]

Algorithm

Use two pointers from both ends and swap elements until they meet.

reverse(A):
    l = 0
    r = length(A) - 1

    while l < r:
        swap A[l], A[r]
        l += 1
        r -= 1

Example

Let

A=[8,3,5,1,9] A = [8, 3, 5, 1, 9]
steplrarray
104[9, 3, 5, 1, 8]
213[9, 1, 5, 3, 8]
322stop

Result:

[9,1,5,3,8] [9, 1, 5, 3, 8]

Correctness

At each step, the algorithm swaps symmetric elements around the center. After kk steps, positions 00 through k1k-1 and nkn-k through n1n-1 are in their correct reversed positions.

When the pointers meet or cross, all positions have been processed exactly once, so the array is fully reversed.

Complexity

operationtime
reverseO(n)O(n)

Space usage:

O(1) O(1)

When to Use

Array reversal is appropriate when:

  • reversing order is required
  • used as a building block for other algorithms
  • in-place transformation is preferred

It is less suitable when:

  • the original array must remain unchanged
  • immutability is required, in which case create a copy

Implementation

def reverse(a):
    l, r = 0, len(a) - 1
    while l < r:
        a[l], a[r] = a[r], a[l]
        l += 1
        r -= 1
func Reverse[T any](a []T) {
    l, r := 0, len(a)-1
    for l < r {
        a[l], a[r] = a[r], a[l]
        l++
        r--
    }
}