Recursive Disk Transfer Between Three Pegs
Trees & GraphsModel answerLast updated
Move n disks from one peg to another using a spare peg, one at a time, never placing a larger disk on a smaller one.
You have n disks of distinct sizes sitting on the first of three pegs, arranged with the largest at the bottom and the smallest on top. Your goal is to relocate the entire stack to a different peg.
Rules:
- Transfer exactly one disk per move
- A disk can only be placed on an empty peg or on top of a strictly larger disk
- You have a third peg available as temporary storage
Task:
Implement a function that produces the complete sequence of moves needed to solve the puzzle. Each move should specify which peg to take from and which to place onto. After presenting your solution, analyze its time and space complexity and explain why the approach is correct.
Example:
For n = 3 disks initially on peg 1, targeting peg 3 with peg 2 as spare, one valid solution contains 7 moves that successfully relocate all disks while respecting the size constraint.
Hints
Hint 1
Think about what must happen before and after moving the bottom-most disk
Hint 2
The problem for n disks can be broken down into smaller instances with n-1 disks and different peg assignments
Hint 3
The number of moves follows the recurrence M(n) = 2·M(n-1) + 1 with M(0) = 0
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The core insight is recognizing that the puzzle has recursive substructure. Focus on the largest disk: it cannot move until all smaller disks are out of the way, and when it does move, the destination peg must be empty.
This observation leads to a three-phase strategy:
- Relocate the top n-1 disks from the starting peg to the spare peg (using the destination as temporary space)
- Move the largest disk directly from start to destination
- Relocate those n-1 disks from the spare peg to the destination (using the now-empty starting peg as temporary space)
Phases 1 and 3 are structurally identical to the original problem but with fewer disks and different peg roles. The base case occurs when n = 0, requiring no moves at all.
Why This Works
We can prove correctness by mathematical induction:
Base case (n=0): No disks require no moves—trivially valid.
Inductive step: Assume the method correctly solves the puzzle for k disks. For k+1 disks:
- Phase 1 is valid because the bottom disk remains untouched, acting as a stable base that doesn't interfere with legal moves above it
- Phase 2 is legal since the starting peg now holds only the largest disk, and the destination is empty (all other disks are on the spare)
- Phase 3 mirrors Phase 1—the largest disk now sits at the destination and acts as the floor for rebuilding the stack
Optimality: Any valid solution must clear the largest disk before moving it, then reconstruct above it. This gives minimum moves M(n) ≥ 2·M(n-1) + 1. Our algorithm achieves exactly this bound, yielding M(n) = 2ⁿ - 1 moves.
Implementation
def solve_disk_puzzle(n, start="A", destination="C", spare="B"):
"""
Generate the sequence of moves to transfer n disks.
Returns: List of strings like "A -> C" representing each move
"""
if not isinstance(n, int) or n < 0:
raise ValueError("Number of disks must be a non-negative integer")
return list(_generate_moves(n, start, destination, spare))
def _generate_moves(n, start, destination, spare):
"""Helper generator to produce moves lazily."""
if n == 0:
return
# Phase 1: move n-1 disks out of the way
yield from _generate_moves(n - 1, start, spare, destination)
# Phase 2: move the largest disk
yield f"{start} -> {destination}"
# Phase 3: rebuild the stack at the destination
yield from _generate_moves(n - 1, spare, destination, start)
# Validation helper
def verify_solution(n, moves):
"""Simulate the move sequence to confirm validity."""
pegs = {"A": list(range(n, 0, -1)), "B": [], "C": []}
for move in moves:
source, dest = (peg.strip() for peg in move.split("->"))
if not pegs[source]:
return False # tried to move from empty peg
disk = pegs[source][-1]
if pegs[dest] and pegs[dest][-1] < disk:
return False # larger on smaller violation
pegs[dest].append(pegs[source].pop())
return pegs["C"] == list(range(n, 0, -1))
Complexity Analysis
Time Complexity: Θ(2ⁿ)
Each recursive invocation performs constant work aside from its recursive calls. The total number of moves generated is 2ⁿ - 1, which dominates the runtime. This is optimal—you cannot solve the puzzle in fewer moves, and producing each move in the output requires at least constant time.
Space Complexity:
- Recursion depth: O(n) — the call stack reaches a maximum depth equal to the number of disks
- Output size: Θ(2ⁿ) — the returned list contains exactly 2ⁿ - 1 move strings
- Auxiliary space with generator: O(n) — using
yieldavoids building the full list in memory
Practical limits: With n = 20, you get approximately one million moves (manageable). At n = 30, you cross one billion moves. The legendary n = 64 variant would require over 18 quintillion moves—far beyond any practical computation.
Edge Cases and Considerations
- n = 0: Returns empty sequence
- n = 1: Returns single move directly from start to destination
- Negative n: Raises ValueError
- Large n: The exponential output size becomes the constraint long before recursion depth (which equals n) causes issues
- Custom peg labels: The parameterized design naturally handles any peg naming scheme
Common Mistakes
- Hard-coding peg identities inside the recursion instead of passing them as parameters, which breaks the relabeling needed for subproblems
- Incorrect peg roles in recursive calls—confusing which peg serves as spare vs. destination in each phase
- Wrong complexity claims like O(n) or O(n²)—the exponential nature is unavoidable given the output size
- Missing output format specification, making the solution untestable
Alternative: Iterative Stack-Based Solution
If recursion is prohibited, you can simulate the call stack explicitly:
def solve_iterative(n, start="A", destination="C", spare="B"):
if n < 0:
raise ValueError("n must be non-negative")
moves = []
stack = [(n, start, destination, spare)]
while stack:
task = stack.pop()
if isinstance(task[0], str): # marker for direct move
moves.append(f"{task[1]} -> {task[2]}")
continue
disks, src, dst, tmp = task
if disks == 0:
continue
# Push in reverse order: phase 3, then phase 2, then phase 1
stack.append((disks - 1, tmp, dst, src))
stack.append(("move", src, dst))
stack.append((disks - 1, src, tmp, dst))
return moves
This produces identical output with the same complexity profile but uses an explicit stack instead of the call stack.