Towers of Hanoi
mathematical puzzles
algorithmic problem solving
combinatorial optimization
K pegs challenge

Towers of Hanoi with K pegs

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

Introduction

The three-peg Towers of Hanoi is a standard recursion exercise, but the puzzle becomes much more interesting when you allow k pegs instead of only three. With extra pegs, the simple 2 ** n - 1 formula no longer applies, so the problem turns into a search for the best way to split the tower.

The Three-Peg Baseline

With three pegs, the strategy is fixed. To move n disks from a source peg to a target peg, you move n - 1 disks out of the way, move the largest disk once, and then move the n - 1 disks back on top of it.

That gives the recurrence:

  • 'T(1, 3) = 1'
  • 'T(n, 3) = 2 * T(n - 1, 3) + 1'

The closed form is 2 ** n - 1.

python
1def hanoi_three(n, source, auxiliary, target, moves=None):
2    if moves is None:
3        moves = []
4    if n == 0:
5        return moves
6
7    hanoi_three(n - 1, source, target, auxiliary, moves)
8    moves.append((source, target))
9    hanoi_three(n - 1, auxiliary, source, target, moves)
10    return moves
11
12
13print(hanoi_three(3, "A", "B", "C"))

This works because there is only one spare peg. Once more pegs are available, there are many possible ways to stage the smaller disks.

The Frame-Stewart Idea

For k pegs, a practical strategy is:

  1. move the top m disks to a spare peg using all k pegs
  2. move the remaining n - m disks to the target using only k - 1 pegs
  3. move the stored m disks onto the target using all k pegs

That gives the Frame-Stewart recurrence:

  • 'T(n, k) = min over m of 2 * T(m, k) + T(n - m, k - 1)'

The best split value m depends on the number of disks and the number of pegs, so you usually compute it with dynamic programming.

Computing the Minimum Move Count

Memoization makes the recurrence practical because the same subproblems appear over and over.

python
1from functools import lru_cache
2
3
4@lru_cache(maxsize=None)
5def min_moves(n, k):
6    if n == 0:
7        return 0
8    if n == 1:
9        return 1
10    if k == 3:
11        return (1 << n) - 1
12
13    best = float("inf")
14    for m in range(1, n):
15        best = min(best, 2 * min_moves(m, k) + min_moves(n - m, k - 1))
16    return best
17
18
19for disks in range(1, 7):
20    print(disks, min_moves(disks, 4))

For the common four-peg variant, this gives the minimal move counts for small and medium inputs very quickly. A naive recursive version is much slower because it recomputes the same n, k states repeatedly.

Reconstructing a Strategy

If you need the move sequence rather than only the count, store the best split for each state and reuse it during a second recursive pass.

python
1@lru_cache(maxsize=None)
2def best_split(n, k):
3    if k == 3:
4        return n - 1
5
6    best_m = 1
7    best_cost = float("inf")
8    for m in range(1, n):
9        cost = 2 * min_moves(m, k) + min_moves(n - m, k - 1)
10        if cost < best_cost:
11            best_cost = cost
12            best_m = m
13    return best_m

The move generator is longer because it must track which pegs are acting as source, target, and temporary storage, but it follows the same three-phase pattern.

Common Pitfalls

The biggest mistake is applying the three-peg formula to the k-peg puzzle. Once more than three pegs exist, 2 ** n - 1 is no longer the general answer.

Another issue is skipping memoization. The recurrence has heavy overlap, so plain recursion becomes expensive surprisingly fast.

Some solutions also hard-code a split rule that works for a few sample cases but is not actually optimal. The whole point of the Frame-Stewart approach is to test candidate split values and keep the cheapest one.

Finally, a correct counting function does not automatically mean the move list is valid. When generating the sequence, you must still respect the rule that a larger disk can never be placed on a smaller disk.

Summary

  • The classic three-peg puzzle has the closed form 2 ** n - 1.
  • The multi-peg version is usually modeled with the Frame-Stewart recurrence.
  • Memoization is essential because the same subproblems repeat.
  • Extra pegs help only if you choose a good split point for the top block.
  • Computing the move count and emitting a valid move sequence are separate tasks.

Related reading
Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

All Rights Reserved.