Algorithms · Two pointers
Reverse a list in place
Reverse a list of letters without making a second list.
The problem
Reverse the list chars in place: change the list you were given rather than building a new one, then return it.
reverse(["h", "e", "l", "l", "o"])→["o", "l", "l", "e", "h"]reverse(["H", "a", "n", "n", "a", "h"])→["h", "a", "n", "n", "a", "H"]Start with the way that works
This version is correct. It is also the slow one. Read it first: the fast way is easier to find once you can see what the slow way wastes.
def reverse(chars):take a list of letters out = []start a new, empty list for c in chars:for each letter, left to right out.insert(0, c)squeeze it in at the very front (everything shuffles along!) chars[:] = outcopy the result back into the original list return charshand it backNow ask: what if there were a billion?
In place also means no second copy. When a file is 10 GB, you often can’t afford another 10 GB, so databases and video editors rearrange data where it already sits.
Aim for O(n)🌱 warm-up
Think it through
new.insert(0, c) looks like one step. Is it?
- Yes
- No: every letter already there shuffles along to make room
Show the answer
No: every letter already there shuffles along to make room. Inserting at the front of a list is a hidden loop. Do it n times and it’s n × n. Knowing which list operations are secretly slow is half of Big-O in Python.
Without a second list, which two letters should swap first?
- The first and the last
- The first and the second
Show the answer
The first and the last. Swap the ends, then move both fingers inwards and repeat until they meet: n/2 swaps, no extra space. That’s two pointers.
Stuck? 3 nudges, smallest first
insert(0, c)looks like one step, but Python has to shuffle every letter along to make room. That’s a hidden loop.- Put one finger on the first letter and one on the last. Swap them, then move both fingers inwards.
i, j = 0, len(chars) - 1. Whilei < j: swapchars[i]andchars[j], theni += 1andj -= 1.
The fast way
Try it yourself before you open this. The slow version above already passes every test, so you can change it one step at a time.
Show the fast version
def reverse(chars):take a list of letters i, j = 0, len(chars) - 1one finger at each end while i < j:until the fingers meet chars[i], chars[j] = chars[j], chars[i]swap the two letters i += 1left finger steps right j -= 1right finger steps left return charsthe same list, reversedSolve it yourself.
It runs right in the page: the tests, the gremlins that try to break it, and a race up to a billion. Free, nothing to install.