Tower of Hanoi

Medium Recursion & Backtracking Basic Recursion

Tower of Hanoi is a medium recursion & backtracking problem solved with the basic recursion pattern. The best approach, iterative (the smallest-disk rule), runs in O(2^n) time and O(n) space. Below are 3 approaches in Java, Python, C++ and JavaScript, from recursion up.

Problem

There are three rods, numbered 1, 2 and 3. Rod 1 holds n disks of different sizes, stacked from the largest at the bottom to the smallest at the top. The disks are numbered by size: disk 1 is the smallest and disk n is the largest.

Move the whole stack to rod 3, following these rules:

  • Only one disk moves at a time, and it must be the top disk of some rod.
  • A moved disk is placed on top of another rod (which may be empty).
  • A disk may never be placed on top of a smaller disk.

Return the moves of the shortest possible solution, in order. Write each move as [disk, from, to]: the number of the disk that moves, the rod it leaves and the rod it lands on. The shortest solution is unique and has 2^n - 1 moves.

Examples

Example 1

Input
n = 1
Output
[[1,1,3]]
Why
With one disk there is nothing in the way: move it straight from rod 1 to rod 3.

Example 2

Input
n = 2
Output
[[1,1,2],[2,1,3],[1,2,3]]
Why
Park the small disk on rod 2, move the big disk to rod 3, then put the small disk back on top of it. Three moves.

Example 3

Input
n = 3
Output
[[1,1,3],[2,1,2],[1,3,2],[3,1,3],[1,2,1],[2,2,3],[1,1,3]]
Why
The first three moves carry the top two disks to rod 2 (using rod 3 as the spare), the fourth moves disk 3 to rod 3, and the last three carry the two disks from rod 2 onto it (using rod 1 as the spare). Seven moves, which is 2^3 - 1.

Constraints

  • 1 <= n <= 16
  • Disks are numbered 1 (smallest) to n (largest); rods are numbered 1, 2 and 3.
  • The answer has exactly 2^n - 1 moves.

Solve it here

Write your solution in Java, Python, C++ or JavaScript and run it against the examples, right in the page. Submit runs the hidden tests too and, with a free account, records the solve in your revision log.

00:00
Testcase

Run checks the testcases above (3 examples, or your own). Submit also runs 8 hidden tests and saves the solve to your log. Signed in, every Run and Submit is saved under My submissions; your draft stays in this browser.

Animated walkthrough

A narrated, step-by-step animation that builds the solution from the idea up. Press play, or step through it at your own pace.

Concepts first, then the problem and every approach, step by step.

Space to play or pause · ← → to jump a step · click or drag the bar to seek

Solutions

Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the code in Java, Python, C++ and JavaScript.

ApproachTimeSpace
RecursionO(2^n)O(n)
Explicit stack (recursion by hand)O(2^n)O(n)
Iterative (the smallest-disk rule)O(2^n)O(n)

1Recursion

TimeO(2^n)The number of moves M(n) satisfies M(n) = 2 M(n - 1) + 1, which is 2^n - 1, and each call does constant work besides its two calls.
SpaceO(n)The recursion is n calls deep. The output list itself holds 2^n - 1 moves and is not counted.

To get the biggest disk n from rod from to rod to, everything above it must first be out of the way, and the only place left is the spare rod. So: move the top n - 1 disks from from to the spare (a smaller copy of the same puzzle), move disk n, then move those n - 1 disks from the spare onto to. Moving zero disks does nothing, which ends the recursion. Each smaller copy just has the roles of the rods swapped.

  1. solve(n, from, to, via): if n == 0, return.
  2. solve(n - 1, from, via, to) to clear the way.
  3. Record the move [n, from, to].
  4. solve(n - 1, via, to, from) to rebuild the tower on top of disk n.
  5. Call solve(n, 1, 3, 2) and return the list of moves.
class Solution {
    public List<List<Integer>> towerOfHanoi(int n) {
        List<List<Integer>> moves = new ArrayList<>();
        solve(n, 1, 3, 2, moves);
        return moves;
    }

    private void solve(int n, int from, int to, int via, List<List<Integer>> moves) {
        if (n == 0) return;
        solve(n - 1, from, via, to, moves);
        moves.add(List.of(n, from, to));
        solve(n - 1, via, to, from, moves);
    }
}

2Explicit stack (recursion by hand)

TimeO(2^n)Every job is pushed and popped once; there are 2^n - 1 disk jobs and about as many tower jobs.
SpaceO(n)Each level of the plan leaves at most two jobs waiting, so the stack holds at most about 2n jobs.

The same plan without the call stack. Keep a stack of jobs. A job is either a tower job (move d disks from one rod to another) or a disk job (move just disk d). Popping a tower job with d > 0 replaces it by its three parts, pushed in reverse so they come off in the right order: the first sub-tower, then the big disk, then the second sub-tower. Popping a disk job records the move. The moves come out in exactly the order the recursion makes them.

  1. Push the tower job {n, 1, 3, 2}.
  2. Pop a job. If it is a disk job, record [d, from, to].
  3. If it is a tower job with d > 0, push {d - 1, via, to, from}, then the disk job {d, from, to}, then {d - 1, from, via, to}.
  4. Repeat until the stack is empty.
class Solution {
    public List<List<Integer>> towerOfHanoi(int n) {
        List<List<Integer>> moves = new ArrayList<>();
        Deque<int[]> stack = new ArrayDeque<>();
        // a job is {disks, from, to, via, kind}; kind 0 = move a tower, kind 1 = move one disk
        stack.push(new int[] { n, 1, 3, 2, 0 });
        while (!stack.isEmpty()) {
            int[] job = stack.pop();
            int d = job[0], from = job[1], to = job[2], via = job[3];
            if (job[4] == 1) {
                moves.add(List.of(d, from, to));
            } else if (d > 0) {
                stack.push(new int[] { d - 1, via, to, from, 0 });
                stack.push(new int[] { d, from, to, via, 1 });
                stack.push(new int[] { d - 1, from, via, to, 0 });
            }
        }
        return moves;
    }
}

3Iterative (the smallest-disk rule)

TimeO(2^n)There are 2^n - 1 moves and each takes constant time.
SpaceO(n)The three rods hold n disks between them.

The optimal sequence has a simple rhythm. Disk 1 moves on every odd-numbered move, always one step around the rods in the same direction: 1 → 2 → 3 → 1 when n is even, and 1 → 3 → 2 → 1 when n is odd. On every even-numbered move, disk 1 stays put, and between the other two rods exactly one move is legal: the smaller of their two top disks goes onto the other rod (or onto it if it is empty). Simulating the three rods as stacks with this rule produces the same 2^n - 1 moves with no recursion at all.

  1. Put disks n..1 on rod 1. step = 1 if n is even, else 2. small = 1 (the rod holding disk 1).
  2. For m = 1 .. 2^n - 1: if m is odd, move disk 1 from rod small to rod (small - 1 + step) % 3 + 1 and update small.
  3. If m is even, look at the two rods a and b that do not hold disk 1 and move the smaller top disk onto the other rod.
  4. Record every move as [disk, from, to].
class Solution {
    public List<List<Integer>> towerOfHanoi(int n) {
        List<List<Integer>> moves = new ArrayList<>();
        List<Deque<Integer>> rods = new ArrayList<>();
        for (int i = 0; i <= 3; i++) rods.add(new ArrayDeque<>());
        for (int d = n; d >= 1; d--) rods.get(1).push(d);
        int step = n % 2 == 0 ? 1 : 2;   // disk 1 walks 1 -> 2 -> 3 (n even) or 1 -> 3 -> 2 (n odd)
        int small = 1;
        int total = (1 << n) - 1;
        for (int m = 1; m <= total; m++) {
            if (m % 2 == 1) {
                int next = (small - 1 + step) % 3 + 1;
                rods.get(next).push(rods.get(small).pop());
                moves.add(List.of(1, small, next));
                small = next;
            } else {
                int a = small % 3 + 1, b = a % 3 + 1;   // the two rods without disk 1
                Deque<Integer> ra = rods.get(a), rb = rods.get(b);
                if (rb.isEmpty() || (!ra.isEmpty() && ra.peek() < rb.peek())) {
                    moves.add(List.of(ra.peek(), a, b));
                    rb.push(ra.pop());
                } else {
                    moves.add(List.of(rb.peek(), b, a));
                    ra.push(rb.pop());
                }
            }
        }
        return moves;
    }
}

Edge cases to test

  • n = 1: a single move [1,1,3]
  • The number of moves doubles with each extra disk (plus one): 2^n - 1 in total
  • Disk 1 moves on every odd-numbered move; it is the only disk that moves that often
  • The middle move, number 2^(n-1), always takes disk n from rod 1 to rod 3
  • Which way the smallest disk travels depends on whether n is odd or even
  • Rod numbers are 1-based, not 0-based

Hints

Hint 1

The largest disk has to move from rod 1 to rod 3 at some point. Where must all the other disks be at that moment?

Hint 2

Moving n - 1 disks to the spare rod is the same puzzle, only smaller and with the rods renamed. Solve it the same way.

Hint 3

Without recursion: the smallest disk moves on every other turn, always around the rods in the same direction. In between, only one other move is legal.

FAQ

What is the best time complexity for Tower of Hanoi?

Iterative (the smallest-disk rule) runs in O(2^n) time and O(n) extra space. There are 2^n - 1 moves and each takes constant time.

Which pattern does Tower of Hanoi use?

It is a recursion & backtracking problem that uses the basic recursion pattern. Other problems with the same pattern: Factorial of a number, Fibonacci Number, Binary Tree Inorder Traversal (Recursive).

Is there a brute force solution for Tower of Hanoi?

Yes. Recursion takes O(2^n) time and O(n) space. To get the biggest disk n from rod from to rod to, everything above it must first be out of the way, and the only place left is the spare rod.

Which edge cases should I test for Tower of Hanoi?

n = 1: a single move [1,1,3]; The number of moves doubles with each extra disk (plus one): 2^n - 1 in total; Disk 1 moves on every odd-numbered move; it is the only disk that moves that often; The middle move, number 2^(n-1), always takes disk n from rod 1 to rod 3; Which way the smallest disk travels depends on whether n is odd or even; Rod numbers are 1-based, not 0-based.