Recursion

O(2ⁿ)·O(n) space
hanoi(3, A→C)n = 3, via B
  • Running

Call hanoi(3, A→C).

Call hanoi(3, A→C).
  1. 1to move n discs from one peg to another, using the third as a spare
  2. 2if there is only one disc, move it straight to its destination
  3. 3otherwise, move the top n minus 1 discs out of the way, onto the spare peg first
  4. 4move the single largest disc directly to its destination
  5. 5move the n minus 1 discs waiting on the spare peg onto the destination, on top of the disc that just arrived
  6. 6all n discs are now stacked on the destination peg, in order, so hand back
Calls
1
Deepest stack
1
Discs moved
0

Complexity

BestO(2ⁿ)
AverageO(2ⁿ)
WorstO(2ⁿ)
Extra spaceO(n)
2ⁿ − 1 at n=3 predicts 7; this run took 1.

Towers of Hanoi

Towers of Hanoi moves n discs from one peg to another, using a third peg as a spare, under the rule that a larger disc may never sit on a smaller one. The recursive solution moves the top n − 1 discs onto the spare peg, moves the single largest disc directly to its destination, then moves the n − 1 discs from the spare peg onto the destination, on top of the disc that just arrived.

When it is the right choice

Towers of Hanoi is not a problem anyone needs to solve outside a classroom, but the recursive solution is provably optimal: it is impossible to solve n discs in fewer than 2ⁿ − 1 moves, and this solution makes exactly that many. Its value here is structural — it is the first algorithm on this page whose recursive calls do real work both before and after the call they make, rather than only building toward a base case.

How it works

Worth noticing

Cost

Best
O(2ⁿ)
Average
O(2ⁿ)
Worst
O(2ⁿ)
Extra space
O(n)
Largest input
n = 8

The largest input is a pedagogical ceiling rather than a technical one. This algorithm makes 2ⁿ − 1 calls, and past n = 8 the run stops being something a person can sit and watch — long before it reaches the step limit the tool enforces.

Worth comparing

All recursive algorithms