Recursion
Towers of Hanoi
Algorithm
Computer Science
Problem Solving

Understanding recursion in the context of Towers of Hanoi

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

Towers of Hanoi is one of the best examples for learning recursion because the problem naturally decomposes into smaller copies of itself. Instead of memorizing calls, the goal is to understand why the recursive breakdown is correct. Once that mental model is clear, many other recursive algorithms become easier to reason about.

Problem Rules and Recursive Shape

The puzzle has three rods and n disks of different sizes. You must move the full stack from source rod to destination rod using an auxiliary rod.

Rules:

  • Move one disk at a time.
  • Only top disk of a rod can be moved.
  • Never place a larger disk on a smaller disk.

The recursive insight:

  1. Move top n - 1 disks from source to auxiliary.
  2. Move largest disk from source to destination.
  3. Move n - 1 disks from auxiliary to destination.

Steps 1 and 3 are the same problem at smaller size, so recursion fits directly.

Base Case and Call Stack Intuition

The base case is n == 1: move one disk directly.

Recursive relation:

  • T(1) = 1
  • T(n) = 2 * T(n - 1) + 1

This gives minimum moves 2^n - 1.

For n = 3, the algorithm makes seven moves. You can visualize recursion as a call tree where each node expands into two smaller subproblems around one direct move.

Python Implementation

The following implementation prints each move and counts total moves.

python
1
2def hanoi(n, source, target, auxiliary, moves):
3    if n == 1:
4        move = f"Move disk 1 from {source} to {target}"
5        moves.append(move)
6        return
7
8    hanoi(n - 1, source, auxiliary, target, moves)
9    moves.append(f"Move disk {n} from {source} to {target}")
10    hanoi(n - 1, auxiliary, target, source, moves)
11
12
13def solve_hanoi(n):
14    moves = []
15    hanoi(n, "A", "C", "B", moves)
16    return moves
17
18
19result = solve_hanoi(3)
20for step in result:
21    print(step)
22print("total moves", len(result))

This code is intentionally explicit and easy to trace in a debugger.

Trace Example for Three Disks

For n = 3, output sequence is:

  1. Move disk 1 from A to C
  2. Move disk 2 from A to B
  3. Move disk 1 from C to B
  4. Move disk 3 from A to C
  5. Move disk 1 from B to A
  6. Move disk 2 from B to C
  7. Move disk 1 from A to C

Each move is valid, and this is optimal by the recurrence proof.

Why Recursion Beats Ad Hoc Rules Here

You can solve small Hanoi cases manually, but manual rule systems become fragile as n grows. Recursion gives:

  • A correctness argument based on subproblem structure.
  • A predictable implementation pattern.
  • A direct path to complexity analysis.

The same technique applies to tree traversal, divide-and-conquer sorting, and backtracking algorithms.

Iterative Alternative and Tradeoffs

Hanoi also has iterative solutions using bit patterns or explicit stacks. These can avoid function call overhead, but they are harder for beginners to verify. For learning recursion concepts, the recursive solution is clearer because problem structure and code structure are aligned.

If recursion depth is a concern in a language with small stack limits, iterative simulation may be needed for large n.

Testing and Verification Tips

Useful tests:

  • n = 1 should produce exactly one move.
  • n = 2 should produce three moves.
  • General check: move count equals 2^n - 1.
  • Validate no move places larger disk on smaller one.

A simple validator can replay moves and assert stack ordering constraints. This turns conceptual correctness into executable checks.

python
1
2def expected_moves(n):
3    return 2 ** n - 1
4
5for n in range(1, 6):
6    m = solve_hanoi(n)
7    assert len(m) == expected_moves(n)

Common Pitfalls

A common pitfall is skipping the base case or placing it after recursive calls, which causes infinite recursion. Another issue is mixing up destination and auxiliary rods in recursive arguments. Teams also sometimes treat recursion as magic and never trace one full example, which leads to shallow understanding. Off-by-one mistakes in disk numbering are frequent in custom visualizations. Finally, learners often focus only on syntax and miss the recurrence relation, which is the core reason the algorithm works.

Summary

  • Towers of Hanoi is a direct demonstration of recursive problem decomposition.
  • Base case handles one disk, recursive case handles n - 1 around one direct move.
  • Minimum move count is 2^n - 1.
  • Recursive code is concise and aligns with formal reasoning.
  • Tracing small examples and validating move counts builds strong recursion intuition.

Course illustration
Course illustration

All Rights Reserved.