Tower of Hanoi
Move a tower of disks to another peg, one disk at a time, never putting a larger disk on a smaller one. The recursive answer is three lines, and it is provably the fastest.
The Puzzle and Its Rules
- One disk at a time – each move lifts exactly one disk.
- Top disk only – a disk can move only if nothing is on top of it.
- No larger on smaller – a disk may be placed only on an empty peg or on a larger disk.
The Tower of Hanoi is a puzzle with three pegs and n disks of different sizes. The disks start stacked on the first peg in decreasing size, largest at the bottom. The goal is to move the whole stack to another peg.
It is the standard first example of recursion because the problem contains a smaller copy of itself. Moving n disks requires moving n − 1 disks twice, and nothing else can work. The puzzle was published by Édouard Lucas in 1883 with a legend of 64 golden disks.
- Three pegs: source, target and spare (auxiliary)
- n disks start on the source in decreasing size
The Recursive Solution
- Base case – if n = 1, move the disk from source to target and return.
- Park – move the top n − 1 disks from source to spare, using target as the helper.
- Move – move disk n from source to target.
- Rebuild – move the n − 1 disks from spare to target, using source as the helper.
Look at the largest disk. It has to move from the source to the target at some point, and when it does, every other disk must be off both pegs, because nothing may sit under it and it may not sit on anything smaller. So all n − 1 smaller disks must be on the spare at that moment.
That observation is the algorithm. Get n − 1 disks onto the spare (the same puzzle with one disk fewer), move the largest disk, then move the n − 1 disks from the spare onto it (the same smaller puzzle again). The pegs swap roles in each recursive call, which is the only subtle part.
Correctness follows by induction. One disk is moved directly. If the method works for n − 1 disks, the three steps move n disks legally, because the largest disk sits at the bottom of every peg it visits and never blocks the smaller disks moving over it.
- Call 1 swaps target and spare; call 2 swaps source and spare
- The largest disk moves exactly once
- Edge case n = 0: nothing to move; the code uses this as its base case, so n = 1 needs no special branch
Why It Takes 2ⁿ − 1 Moves
Let T(n) be the number of moves for n disks. The algorithm makes two calls of size n − 1 and one move, so T(n) = 2T(n − 1) + 1 with T(1) = 1.
Unrolling it: T(n) = 2T(n − 1) + 1 = 4T(n − 2) + 2 + 1 = … = 2ⁿ⁻¹ + 2ⁿ⁻² + … + 2 + 1 = 2ⁿ − 1. Adding 1 to both sides gives T(n) + 1 = 2(T(n − 1) + 1), which doubles each time: another way to see the closed form.
No method can do better. The largest disk must move at least once, and before its first move the other n − 1 disks must all be on the spare. After its last move they must all end up on top of it. Each of those needs at least T(n − 1) moves, so any solution takes at least 2T(n − 1) + 1.
| Disks n | Moves 2ⁿ − 1 | Time at 1 move/s |
|---|---|---|
| 3 | 7 | 7 seconds |
| 5 | 31 | 31 seconds |
| 10 | 1,023 | about 17 minutes |
| 20 | 1,048,575 | about 12 days |
| 64 | 18,446,744,073,709,551,615 | about 585 billion years |
- Each extra disk doubles the move count and adds one
Terms, operations, and practical uses
Core vocabulary
- Source, target, spareThe peg the disks start on, the peg they end on, and the helper peg.
- Base caseOne disk: move it directly. Without it the recursion never stops.
- RecurrenceT(n) = 2T(n − 1) + 1, the move count expressed in terms of itself.
- Lower boundNo solution can use fewer than 2ⁿ − 1 moves.
Numbers to remember
- 3 disks7 moves; disk 1 moves 4 times, disk 2 twice, disk 3 once.
- Disk kMoves 2ⁿ⁻ᵏ times in the optimal solution.
- TimeO(2ⁿ), matched by the size of the output.
- SpaceO(n): the call stack is as deep as the number of disks.
Related lessons
- RecursionBase cases, recursive cases and the call stack in general.
- Divide and ConquerSplitting into subproblems and solving recurrences.
- Time and Space ComplexityWhere O(2ⁿ) sits against polynomial growth.
- StacksThe structure behind every recursive call, and each peg.
Code in Python, C++ and Java
def hanoi(n, source, target, spare, moves):
if n == 0:
return
hanoi(n - 1, source, spare, target, moves) # park the n - 1 smaller disks
moves.append((n, source, target)) # the largest disk moves once
hanoi(n - 1, spare, target, source, moves) # bring them back on top
def iterative_hanoi(n):
pegs = {"A": list(range(n, 0, -1)), "B": [], "C": []}
# The smallest disk cycles A -> C -> B for odd n, A -> B -> C for even n.
cycle = ["A", "C", "B"] if n % 2 else ["A", "B", "C"]
moves = []
smallest_at = 0
for step in range(2**n - 1):
if step % 2 == 0:
source = cycle[smallest_at]
smallest_at = (smallest_at + 1) % 3
target = cycle[smallest_at]
else:
# The only legal move that does not touch the smallest disk.
x, y = [p for p in "ABC" if p != cycle[smallest_at]]
if not pegs[x] or (pegs[y] and pegs[y][-1] < pegs[x][-1]):
x, y = y, x
source, target = x, y
pegs[target].append(pegs[source].pop())
moves.append((pegs[target][-1], source, target))
return moves
moves = []
hanoi(3, "A", "C", "B", moves)
for i, (disk, source, target) in enumerate(moves, 1):
print(f"Move {i}: disk {disk} from {source} to {target}")
print("Total moves:", len(moves))
print("Iterative gives the same moves:", iterative_hanoi(3) == moves)
for n in range(1, 11):
count = []
hanoi(n, "A", "C", "B", count)
print(f"n = {n:2}: {len(count):4} moves (2^n - 1 = {2**n - 1})")#include <cstdio>
#include <iostream>
#include <tuple>
#include <vector>
using Move = std::tuple<int, char, char>; // disk, from, to
void hanoi(int n, char source, char target, char spare, std::vector<Move>& moves) {
if (n == 0) return;
hanoi(n - 1, source, spare, target, moves); // park the n - 1 smaller disks
moves.emplace_back(n, source, target); // the largest disk moves once
hanoi(n - 1, spare, target, source, moves); // bring them back on top
}
std::vector<Move> iterativeHanoi(int n) {
std::vector<int> pegs[3];
for (int d = n; d >= 1; d--) pegs[0].push_back(d);
const char name[3] = {'A', 'B', 'C'};
// The smallest disk cycles A -> C -> B for odd n, A -> B -> C for even n.
const int cycle[3] = {0, n % 2 ? 2 : 1, n % 2 ? 1 : 2};
std::vector<Move> moves;
int smallestAt = 0;
for (int step = 0; step < (1 << n) - 1; step++) {
int source, target;
if (step % 2 == 0) {
source = cycle[smallestAt];
smallestAt = (smallestAt + 1) % 3;
target = cycle[smallestAt];
} else {
// The only legal move that does not touch the smallest disk.
int x = -1, y = -1;
for (int p = 0; p < 3; p++) {
if (p == cycle[smallestAt]) continue;
(x == -1 ? x : y) = p;
}
if (pegs[x].empty() || (!pegs[y].empty() && pegs[y].back() < pegs[x].back())) {
std::swap(x, y);
}
source = x;
target = y;
}
pegs[target].push_back(pegs[source].back());
pegs[source].pop_back();
moves.emplace_back(pegs[target].back(), name[source], name[target]);
}
return moves;
}
int main() {
std::vector<Move> moves;
hanoi(3, 'A', 'C', 'B', moves);
for (size_t i = 0; i < moves.size(); i++) {
auto [disk, source, target] = moves[i];
std::cout << "Move " << i + 1 << ": disk " << disk << " from " << source << " to " << target
<< '\n';
}
std::cout << "Total moves: " << moves.size() << '\n';
std::cout << "Iterative gives the same moves: "
<< (iterativeHanoi(3) == moves ? "True" : "False") << '\n';
for (int n = 1; n <= 10; n++) {
std::vector<Move> count;
hanoi(n, 'A', 'C', 'B', count);
std::printf("n = %2d: %4zu moves (2^n - 1 = %d)\n", n, count.size(), (1 << n) - 1);
}
}import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.List;
public class Main {
record Move(int disk, char source, char target) {}
static void hanoi(int n, char source, char target, char spare, List<Move> moves) {
if (n == 0) return;
hanoi(n - 1, source, spare, target, moves); // park the n - 1 smaller disks
moves.add(new Move(n, source, target)); // the largest disk moves once
hanoi(n - 1, spare, target, source, moves); // bring them back on top
}
static List<Move> iterativeHanoi(int n) {
List<Deque<Integer>> pegs = List.of(new ArrayDeque<>(), new ArrayDeque<>(), new ArrayDeque<>());
for (int d = n; d >= 1; d--) pegs.get(0).push(d);
char[] name = {'A', 'B', 'C'};
// The smallest disk cycles A -> C -> B for odd n, A -> B -> C for even n.
int[] cycle = {0, n % 2 == 1 ? 2 : 1, n % 2 == 1 ? 1 : 2};
List<Move> moves = new ArrayList<>();
int smallestAt = 0;
for (int step = 0; step < (1 << n) - 1; step++) {
int source, target;
if (step % 2 == 0) {
source = cycle[smallestAt];
smallestAt = (smallestAt + 1) % 3;
target = cycle[smallestAt];
} else {
// The only legal move that does not touch the smallest disk.
int x = -1, y = -1;
for (int p = 0; p < 3; p++) {
if (p == cycle[smallestAt]) continue;
if (x == -1) x = p;
else y = p;
}
Deque<Integer> px = pegs.get(x), py = pegs.get(y);
if (px.isEmpty() || (!py.isEmpty() && py.peek() < px.peek())) {
int t = x;
x = y;
y = t;
}
source = x;
target = y;
}
pegs.get(target).push(pegs.get(source).pop());
moves.add(new Move(pegs.get(target).peek(), name[source], name[target]));
}
return moves;
}
public static void main(String[] args) {
List<Move> moves = new ArrayList<>();
hanoi(3, 'A', 'C', 'B', moves);
for (int i = 0; i < moves.size(); i++) {
Move m = moves.get(i);
System.out.println("Move " + (i + 1) + ": disk " + m.disk() + " from " + m.source() + " to " + m.target());
}
System.out.println("Total moves: " + moves.size());
System.out.println("Iterative gives the same moves: " + (iterativeHanoi(3).equals(moves) ? "True" : "False"));
for (int n = 1; n <= 10; n++) {
List<Move> count = new ArrayList<>();
hanoi(n, 'A', 'C', 'B', count);
System.out.printf("n = %2d: %4d moves (2^n - 1 = %d)%n", n, count.size(), (1 << n) - 1);
}
}
}Step through it
Running on n = 3, from A to C using B
Time and Space Complexity
The algorithm makes one move per call that reaches the move line, and it makes exactly 2ⁿ − 1 moves, so the running time is O(2ⁿ). That is not inefficiency: the output itself has 2ⁿ − 1 lines, so no algorithm can print a solution faster.
The space is the depth of the recursion. Each call waits on a call one disk smaller, so at most n frames are on the stack at once: O(n) space. The tracer above shows the stack never holding more than three frames for three disks.
- Space stays small while time explodes: only one path of the recursion tree is live at a time
Solving It Without Recursion
- Odd move – move disk 1 one peg along its cycle (A → C → B for odd n, A → B → C for even n).
- Even move – between the two pegs not holding disk 1, move the smaller top disk onto the other peg.
- Repeat – until 2ⁿ − 1 moves are made.
The moves follow a fixed pattern, so the puzzle can be solved without recursion. Every odd-numbered move moves the smallest disk, always in the same cyclic direction. Every even-numbered move is the only legal move that does not involve the smallest disk.
The direction depends on parity. For an odd number of disks the smallest disk cycles source → target → spare → source. For an even number it cycles source → spare → target → source. The code listing checks that this produces exactly the same 7 moves as the recursion for 3 disks.
- Disk 1 moves on every other move: 2ⁿ⁻¹ times in total
- Disk k moves 2ⁿ⁻ᵏ times; the largest moves once
- The even move is always forced: exactly one legal option exists
Where the Puzzle Shows Up
It is the standard exam and interview question on recursion because it shows a program that is three lines long and still exponential. Outside teaching, its move pattern turns up in a few practical places.
- Recurrence relations – the cleanest example of setting up and unrolling T(n) = 2T(n − 1) + 1
- Backup rotation – the Tower of Hanoi backup scheme reuses one tape every 2 days, another every 4, and so on, just as disk k moves every 2ᵏ moves
- Gray code – the disk moved at step k is the bit that changes between k − 1 and k in the binary reflected Gray code
- Psychology – the puzzle is a standard test of planning ability