← Back

Tower of Hanoi Simulator

What is the Tower of Hanoi?

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.

Minimum moves7
RecurrenceT(n) = 2T(n − 1) + 1
Time complexityO(2ⁿ)
Recursion depthO(n)

Simulation controls

500 ms
Tower A — Source
Tower B — Auxiliary
Tower C — Target

The puzzle is ready. Use Next Step or Auto Solve.

Completed moves0
Minimum moves7
Current step0 / 7
Next moveA → C

Move history

  1. No moves completed yet.

Recursive idea

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)

Tower of Hanoi concepts

Base case

When only one disk remains, the solution is a single direct move from the source tower to the target tower.

Recursive decomposition

A problem with n disks is reduced to two problems with n − 1 disks, separated by one move of the largest disk.

Minimum move count

The optimal solution requires exactly 2ⁿ − 1 moves. Each additional disk more than doubles the work.

Connection to stacks

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.

Complexity summary

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.