Java Recursion Program · OT34
Solve the Tower of Hanoi in Java
To move n disks, first move the top n - 1 out of the way, then move the largest disk, then move the n - 1 disks back on top of it. The recursion does the rest.
Problem Statement
Move a stack of n disks from peg A to peg C, using peg B as a helper. Only one disk moves at a time, and a larger disk may never sit on a smaller one.
Print every move in order. The minimum number of moves is 2n − 1.
Input/Output Examples
n = 2Output3 movesExplanation: disk 1 to B, disk 2 to C, disk 1 to C.n = 3Output7 movesExplanation: 23 − 1 = 7.n = 10Output1023 movesExplanation: the count doubles with each extra disk.Visual Explanation
- Move 2 disksA → Bdisk 1 → Cdisk 2 → Bdisk 1 → Bclear the way
- LargestA → Cdisk 3one move
- Move 2 disksB → Cdisk 1 → Adisk 2 → Cdisk 1 → Cbuild on top
- Done3 + 1 + 37 moves
Each level makes two recursive calls on n - 1 disks plus one move, so moves(n) = 2 × moves(n - 1) + 1, which solves to 2n − 1.
Approaches
Both approaches print exactly the same moves. One recurses; the other computes each move from its number.
Approach 1: Recursion (Recommended)
Idea: solve(n, from, to, via) moves n - 1 disks to via, moves disk n, then moves the n - 1 disks onto to.
- If
nis 0, do nothing. - Call
solve(n - 1, from, via, to). - Record the move of disk
nfromfromtoto. - Call
solve(n - 1, via, to, from).
Time: O(2n) · Space: O(n). Recursion depth, excluding the list of moves.
Approach 2: Iterative With Bit Tricks
Idea: move number i moves disk trailingZeros(i) + 1 from peg (i & (i - 1)) % 3 to ((i | (i - 1)) + 1) % 3.
- Loop
ifrom 1 to2n − 1. - Compute the disk and the two pegs from
i. - Map peg numbers to letters; the mapping swaps B and C when
nis even.
Time: O(2n) · Space: O(1). Excluding the list of moves.
Java Solutions
Each tab is a complete program that runs on Java 17 or later. Both programs print the same output for the same inputs.
Approach 1: Recursion (Recommended)
The textbook example of recursion: the code is almost a word-for-word copy of the strategy.
import java.util.ArrayList;
import java.util.List;
public class HanoiRecursive {
// Move n-1 disks out of the way, move the largest disk, then move the n-1 disks on top of it
static void solve(int n, char from, char to, char via, List<String> moves) {
if (n == 0) {
return;
}
solve(n - 1, from, via, to, moves);
moves.add("disk " + n + ": " + from + " -> " + to);
solve(n - 1, via, to, from, moves);
}
public static void main(String[] args) {
for (int n : new int[] {2, 3}) {
List<String> moves = new ArrayList<>();
solve(n, 'A', 'C', 'B', moves);
System.out.println("n=" + n + " (" + moves.size() + " moves): " + String.join(", ", moves));
}
List<String> big = new ArrayList<>();
solve(10, 'A', 'C', 'B', big);
System.out.println("n=10 -> " + big.size() + " moves");
}
}
n=2 (3 moves): disk 1: A -> B, disk 2: A -> C, disk 1: B -> C n=3 (7 moves): disk 1: A -> C, disk 2: A -> B, disk 1: C -> B, disk 3: A -> C, disk 1: B -> A, disk 2: B -> C, disk 1: A -> C n=10 -> 1023 moves
Time complexity: O(2n) · Space complexity: O(n).
Approach 2: Iterative With Bit Tricks
No recursion at all, and any single move can be computed directly from its number.
import java.util.ArrayList;
import java.util.List;
public class HanoiIterative {
// Move number i (1-based) moves disk (trailing zeros of i) + 1, between pegs given by bit tricks
static List<String> solve(int n) {
char[] pegs = (n % 2 == 0) ? new char[] {'A', 'C', 'B'} : new char[] {'A', 'B', 'C'};
List<String> moves = new ArrayList<>();
int total = (1 << n) - 1;
for (int i = 1; i <= total; i++) {
int disk = Integer.numberOfTrailingZeros(i) + 1;
int from = (i & (i - 1)) % 3;
int to = ((i | (i - 1)) + 1) % 3;
moves.add("disk " + disk + ": " + pegs[from] + " -> " + pegs[to]);
}
return moves;
}
public static void main(String[] args) {
for (int n : new int[] {2, 3}) {
List<String> moves = solve(n);
System.out.println("n=" + n + " (" + moves.size() + " moves): " + String.join(", ", moves));
}
System.out.println("n=10 -> " + solve(10).size() + " moves");
}
}
n=2 (3 moves): disk 1: A -> B, disk 2: A -> C, disk 1: B -> C n=3 (7 moves): disk 1: A -> C, disk 2: A -> B, disk 1: C -> B, disk 3: A -> C, disk 1: B -> A, disk 2: B -> C, disk 1: A -> C n=10 -> 1023 moves
Time complexity: O(2n) · Space complexity: O(1).
Complexity Analysis
| Approach | Time Complexity | Space Complexity |
|---|---|---|
| Recursion | O(2n) | O(n) |
| Iterative With Bit Tricks | O(2n) | O(1) |
Here n is the number of disks. Both approaches produce all 2n − 1 moves, which is also the proven minimum.
Interview Tips and Recommended Approach
- Explain the three steps before writing code; the recursion follows immediately.
- Derive the move count from the recurrence
T(n) = 2T(n - 1) + 1. - Know the pattern. Disk 1 moves every other turn, always cycling through the pegs in the same direction.
- Warn about growth. 64 disks would need about 1.8 × 1019 moves.
Recommended Approach: Recursion
Why: it states the solution exactly as you would explain it, and it is the clearest demonstration of how recursion breaks a problem into smaller copies of itself.