Tower of Hanoi

n − 1, 1 and n − 1 · Part of Strategies

Key idea

Practice

6 questions · about 3 min

Explained step by step

Tower of Hanoi

The Tower of Hanoi has 3 pegs, A, B and C. At the start, A holds n disks, from the biggest at the bottom to the smallest on top. They must all move to C in the same order with 3 rules: only the top disk of a peg can be taken, 1 disk moves at a time, and a big one can never sit on a small one. B helps in the middle.

The base cases are solved by hand. With 1 disk, f(1), 1 move is enough: from A to C. With 2 disks, f(2), B is needed: the small one goes from A to B, the big one from A to C and the small one from B to C, 3 moves. It sums up as «move 2 disks from A to C using B».

If f(n) counts the moves, f(n) = 2 × f(n − 1) + 1, with f(1) = 1. That gives 1, 3, 7, 15, 31...: always 2ⁿ − 1. Each disk added doubles the work and adds 1. With 10 disks it is 1,023 moves; with 20, over 1 million.

The legend says that in a temple in India some monks move 64 gold disks among 3 diamond pegs, and that the world ends when they place the last one. With 64 disks it takes 2⁶⁴ − 1 moves, about 1.84 × 10¹⁹. At 1 move per second that is about 585 billion years, far more than the age of the universe, which is around 13.8 billion.

Divide and conquer

For n disks, the top n − 1 are treated as a block. First those n − 1 move from A to B using C. Then the biggest disk, now alone, goes from A to C. Last, the n − 1 go from B to C using A. That way f(n) splits into 2 problems f(n − 1) and 1 problem f(1), and each f(n − 1) splits the same way down to f(1).

Recursion tree

The recursive function dfs(i, source, helper, target) moves the top i disks from the source to the target. Each call opens 2 calls with i − 1, so the recursion tree has height n and about 2ⁿ nodes: the time is O(2ⁿ). But at any moment only the calls on one path from the root to a leaf are open, at most n: the memory is O(n).

Terms in this lesson

Arki, the beaver mascot

Your next interview starts with 5 minutes today.

Free on iOS and Android. Start from zero, no account needed.

Key idea

n − 1, 1 and n − 1