#1 India's Top IT Training Institute
×

About Uncodemy

Know more about who we are and what we stand for.

About Us

About Us

Discover our mission to equip individuals with essential IT skills and industry expertise.

Read More →
UnCodeMy Gallery

UnCodeMy Gallery

Explore highlights from our IT training sessions and success stories.

Read More →
Mentors

Mentors

Meet the industry experts who train and guide you through your course.

Read More →
Free Resources

Free Resources

Free tutorials, interview questions, tools and calculators to help you learn.

Explore →
×

Free Resources

Learn, practice and plan your career — bilkul free.

Tutorials

Tutorials

Step-by-step written tutorials to learn any technology at your own pace.

Read More →
Free Counselling

Free Counselling

Book a free video counselling session and pick the right course for you.

Read More →
Online Compiler

Online Compiler

Write, run and test your code online — no setup required.

Read More →
Recursion & Problem Solving

Tower of Hanoi in Data Structure

Tower of Hanoi is a classic mathematical puzzle involving three rods and a number of disks of different sizes. The objective is to move the entire stack of disks from the source rod to a destination rod, following specific rules, using an auxiliary rod.

Rules

  • Only one disk can be moved at a time.
  • Each move takes the top disk from one stack and places it on top of another stack or an empty rod.
  • A larger disk may never be placed on top of a smaller disk.

Recursive Solution

To move n disks from the source rod to the destination rod: move the top n-1 disks from source to the auxiliary rod, move the nth (largest) disk from source to destination, then move the n-1 disks from the auxiliary rod to the destination rod.

def tower_of_hanoi(n, source, auxiliary, destination):
    if n == 0:
        return
    tower_of_hanoi(n - 1, source, destination, auxiliary)
    print(f"Move disk {n} from {source} to {destination}")
    tower_of_hanoi(n - 1, auxiliary, source, destination)

tower_of_hanoi(3, 'A', 'B', 'C')

Complexity

MetricValue
TimeO(2^n)
Space (call stack)O(n)

The minimum number of moves required to solve the puzzle for n disks is exactly 2^n − 1.

Applications

  • A classic teaching example for understanding recursion and recurrence relations.
  • Used to illustrate backup rotation schemes (Tower of Hanoi backup rotation in data storage).
  • Basis for algorithmic problems involving state-space search and puzzle solving.

Tracing Every Move for Three Disks

Running the recursive function with three disks on rods A, B and C prints seven moves. Watching them one by one is the fastest way to see how the recursion unfolds, because each block of moves matches one recursive call.

StepDiskFromToWhat is happening
11ACStart clearing the top two disks off A
22ABDisk 2 parks on the helper rod
31CBSmaller pile of two is now on B
43ACThe largest disk makes its only move
51BABegin rebuilding the pile on C
62BCDisk 2 lands on disk 3
71ACPuzzle solved

Steps 1 to 3 solve a two-disk puzzle from A to B, step 4 moves the biggest disk, and steps 5 to 7 solve another two-disk puzzle from B to C. That is the recursive idea written out in plain moves.

Where the 2^n − 1 Count Comes From

Let T(n) be the number of moves needed for n disks. To move the bottom disk, every disk above it must first sit on the spare rod, which costs T(n-1) moves. Then the bottom disk moves once, and the smaller pile is carried back on top of it for another T(n-1) moves. That gives the recurrence T(n) = 2T(n-1) + 1 with T(0) = 0.

Unrolling it gives 1, 3, 7, 15, 31 and so on. Adding one to each value produces powers of two, which is why the closed form is 2^n - 1. No cleverer strategy exists, because the largest disk cannot move until all the others are stacked on a single rod, so the same count is also a lower bound.

The growth is brutal: twenty disks already need over a million moves. That is why the puzzle is a standard example of an exponential-time algorithm.

Solving It Without Recursion

Interviewers sometimes ask for an iterative version. One known approach cycles through three rod pairs and always makes the only legal move between the pair. For an even number of disks the roles of the helper and target rods are swapped.

def hanoi_iterative(n, src='A', aux='B', dst='C'):
    rods = {src: list(range(n, 0, -1)), aux: [], dst: []}
    if n % 2 == 0:
        aux, dst = dst, aux
    pairs = [(src, dst), (src, aux), (aux, dst)]
    moves = []
    for i in range(1, 2 ** n):
        a, b = pairs[(i - 1) % 3]
        if not rods[b] or (rods[a] and rods[a][-1] < rods[b][-1]):
            rods[b].append(rods[a].pop())
            moves.append((a, b))
        else:
            rods[a].append(rods[b].pop())
            moves.append((b, a))
    return moves

print(hanoi_iterative(3))

Each rod is a Python list used as a stack, so the top disk is always the last item. The loop runs exactly 2^n - 1 times, matching the recursive answer.

Slips That Break a Hanoi Solution

  • Swapping arguments in the recursive calls. The first call must use the destination as the helper, and the second call must use the source as the helper. Mixing these up produces illegal moves.
  • Forgetting the base case. Without if n == 0: return the function recurses until Python raises a recursion error.
  • Testing with large n. Printing moves for thirty disks will not finish in any reasonable time. Test with three or four disks and compare the count against 2^n - 1.
  • Confusing time and space. The call stack only grows to depth n, so memory stays linear even though the number of moves is exponential.

Quick self-check: for four disks you should get fifteen moves, and disk 4 should move exactly once, at step eight.