Base case
When only one disk remains, the solution is a single direct move from the source tower to the target tower.
The Tower of Hanoi is a recursive puzzle with three towers and disks of different sizes. Move the entire stack from Tower A to Tower C while obeying three rules: move only one disk at a time, move only the top disk, and never place a larger disk on a smaller disk.
The puzzle is ready. Use Next Step or Auto Solve.
To move 3 disks from A to C: move 2 disks from A to B, move disk 3 from A to C, then move 2 disks from B to C.
hanoi(n, source, target, auxiliary):
if n == 1:
move source → target
return
hanoi(n - 1, source, auxiliary, target)
move source → target
hanoi(n - 1, auxiliary, target, source)
When only one disk remains, the solution is a single direct move from the source tower to the target tower.
A problem with n disks is reduced to two problems with n − 1
disks, separated by one move of the largest disk.
The optimal solution requires exactly 2ⁿ − 1 moves. Each additional disk
more than doubles the work.
Each tower behaves like a stack: only the top disk may be removed, and a disk is placed only on the top of another tower.
| Property | Value | Explanation |
|---|---|---|
| Minimum moves | 2ⁿ − 1 | The recurrence doubles the previous solution and adds one move. |
| Time complexity | O(2ⁿ) | Every recursive level generates two smaller Hanoi calls. |
| Recursion depth | O(n) | The call stack reaches one frame per disk. |
| Auxiliary algorithm space | O(n) | The recursive call stack stores the active subproblems. |