← All Foundations

Arrays & Strings

Foundation drill for this topic

Drill #1 — Reverse array in-place

Easy Two Pointers

In plain English: You're given a list of numbers and need to flip the order without creating a new list.

Two pointers converging from opposite ends is the go-to for symmetric array operations — each swap brings both ends closer to the center.

Prompt

Given an array a, reverse it in-place.

Try to write it from scratch before scrolling down.

Solution

def reverse(a):
    l, r = 0, len(a) - 1
    # converge from both ends
    while l < r:
        a[l], a[r] = a[r], a[l]
        l += 1
        r -= 1
    return a

# Test: reverse([1,2,3,4,5]) == [5,4,3,2,1]
O(n) time · O(1) space

Related Micro Drills

Quick recall drills to reinforce this pattern.

126 Remove duplicates in-place Pointer Manipulation 10s

Write-pointer compaction for sorted arrays. Returns new length.

w = 1
for i in range(1, len(a)):
    if a[i] != a[i-1]:
        a[w] = a[i]
        w += 1
return w
86 Remove element in-place Pointer Manipulation 10s

Write-pointer skips unwanted values. O(1) space removal pattern.

w = 0
for r in range(len(a)):
    if a[r] != val:
        a[w] = a[r]
        w += 1
# a[:w] has val removed
116 Rotate matrix 90° CW Interval & Math 15s

Transpose + reverse-rows rotates 90 degrees clockwise in-place. Classic matrix manipulation.

n = len(m)
for i in range(n):
    for j in range(i+1, n):
        m[i][j], m[j][i] = m[j][i], m[i][j]
for row in m:
    row.reverse()
See all drills in Arrays & Strings →