Medium Logical Thinking Java

Tower of Hanoi Program in Java Using Recursion

Print the moves that solve the Tower of Hanoi for n disks.

  • TimeO(2^n)
  • SpaceO(n) for the recursion stack
  • Hints3
  • Read3 min
Quick answer

To move n disks from A to C, first move n - 1 disks from A to B, then move the biggest disk from A to C, then move the n - 1 disks from B to C. In Java this is a method that calls itself twice. It takes 2^n - 1 moves, so 3 disks need 7 moves.

RecursionDivide and conquerBase case
1

Problem statement

Write a Tower of Hanoi program in Java using recursion. There are three rods, A, B and C. Rod A holds n disks, biggest at the bottom. Move them all to rod C.

Rules:

  • Move one disk at a time.
  • Only the top disk of a rod can move.
  • Never put a bigger disk on a smaller one.
Input

The number of disks n.

Output

Each move on its own line, then the total number of moves.

Examples

Example 1
Inputn = 3
OutputMove disk 1 from A to C Move disk 2 from A to B Move disk 1 from C to B Move disk 3 from A to C Move disk 1 from B to A Move disk 2 from B to C Move disk 1 from A to C Total moves: 7

3 disks need 2^3 - 1 = 7 moves.

Example 2
Inputn = 1
OutputMove disk 1 from A to C Total moves: 1

One disk goes straight to C.

Constraints

  • 1 <= n <= 20, because the number of moves doubles with each disk
2

Think before you code

Reveal the questions to ask yourself first
  • What must be true before the biggest disk can move?
  • After it moves, what is left to do?
  • What is the smallest case, where no more calls are needed?
3

Hints

Open one at a time — try again after each.
1 Hint 1
The biggest disk can move only when all the others wait on the helper rod.
2 Hint 2
Moving n - 1 disks is the same problem, only smaller.
3 Hint 3
Call with (n - 1, from, helper, to), print the move, then call with (n - 1, helper, to, from).
4

Approach

Reveal the step-by-step approach

The Tower of Hanoi problem in Java has three steps:

  1. Move the top n - 1 disks from the start rod to the helper rod.
  2. Move the biggest disk from the start rod to the target rod.
  3. Move the n - 1 disks from the helper rod to the target rod.

Steps 1 and 3 are the same problem with one disk less, so the method calls itself. It stops when there are no disks. If recursion is new, first try factorial using recursion.

5

Dry run

Walk through the example step by step

For 3 disks from A to C:

part                       | moves
---------------------------+------------------------
2 disks from A to B        | disk 1: A to C
                           | disk 2: A to B
                           | disk 1: C to B
biggest disk               | disk 3: A to C
2 disks from B to C        | disk 1: B to A
                           | disk 2: B to C
                           | disk 1: A to C
6

Solution

Reveal the full Java solution
Solution.java
public class TowerOfHanoi {
    // Moves n disks and returns how many moves it took.
    public static long solve(int n, char from, char to, char helper) {
        if (n == 0) {
            return 0; // no disk, no move
        }
        long moves = solve(n - 1, from, helper, to);
        System.out.println("Move disk " + n + " from " + from + " to " + to);
        moves++;
        moves += solve(n - 1, helper, to, from);
        return moves;
    }

    public static void main(String[] args) {
        long moves = solve(3, 'A', 'C', 'B');
        System.out.println("Total moves: " + moves); // Total moves: 7
    }
}

This is the Tower of Hanoi in Java using recursion. The trick is in the order of the rod names. In the first call the helper becomes the target. In the second call the helper becomes the start.

Why 2^n - 1 moves

Let M(n) be the moves for n disks. Then M(n) = 2 * M(n - 1) + 1, with M(0) = 0. This gives 1, 3, 7, 15, 31 and so on, which is 2^n - 1. No method can use fewer moves, so no program that prints every move can take fewer steps.

Tower of Hanoi program in Java with user input

This version reads the number of disks. It stops at one disk instead of zero.

import java.util.Scanner;

public class HanoiInput {
    static void move(int n, String from, String to, String helper) {
        if (n == 1) {
            System.out.println("Disk 1: " + from + " -> " + to);
            return;
        }
        move(n - 1, from, helper, to);
        System.out.println("Disk " + n + ": " + from + " -> " + to);
        move(n - 1, helper, to, from);
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("How many disks?");
        int n = sc.nextInt();
        if (n < 1) {
            System.out.println("Enter 1 or more");
            return;
        }
        move(n, "A", "C", "B");
    }
}

For 2 disks it prints these moves after the question:

Disk 1: A -> B
Disk 2: A -> C
Disk 1: B -> C

How deep does the recursion go?

The calls are only about n levels deep at one time, even though there are many calls in total. So memory is small. Time is the limit: 20 disks already need 1,048,575 moves.

Read the Tower of Hanoi in Java code once more and draw the calls on paper. Then practise Fibonacci with recursion, quick sort, and the DSA interview questions. To learn with a trainer, see the Java full stack course.

TimeO(2^n)
SpaceO(n) for the recursion stack
7

Review before the interview

Common mistakes

  • Passing the rods in the same order in both calls.
  • Forgetting the base case, which leads to a StackOverflowError.
  • Printing the move before the first call or after the second one. It must be between them.

Edge cases to test

  • n = 0 prints no moves and returns 0.
  • n = 1 needs one move.
  • A negative n must be rejected before the call.

Interview follow-ups

  • How would you solve it without recursion?
  • How would you print the state of each rod after every move?
  • How does the answer change with four rods?

Keep practising

Practising for Java interviews?

CodeBegun's Java Full Stack with AI program builds this problem-solving muscle with mentor review and mock interviews.

Chat with us