BeginnerCoder

Lesson 8 — Reverse in place

Two pointers, zero extra memory

In place means changing the list you were given instead of building a new one. To reverse in place, put one pointer (an index variable) at the start (i) and one at the end (j). Swap the two items, move i right and j left, and stop when they meet.

# [1, 2, 3, 4, 5]: swap 1<->5, then 2<->4, 3 stays

This uses no extra list, so the memory cost is O(1) — constant, whatever the size.

Why it matters: on huge data (or tiny devices) you cannot always afford a copy. Two pointers is a pattern you will see again in Lesson 14.

Want it another way?
Task

Inside the loop, swap a[i] and a[j], then move i one step right and j one step left.

Run your code — when the output matches the task, you will see a green check. Then mark the lesson complete.

← Back
Next →
Test your knowledge

A quick 3-question quiz on this lesson — instant feedback.

Enjoying this lesson? Share it.