Senior 4 min · March 05, 2026

Tower of Hanoi Recursion — Stack Overflow from Frame Bloat

StackOverflowError on N=32? Excessive logging bloats each stack frame beyond 1MB.

N
Naren · Founder
Plain-English first. Then code. Then the interview question.
About
 ● Production Incident 🔎 Debug Guide
Quick Answer
  • Tower of Hanoi is a recursion puzzle: move N discs from peg A to C using an auxiliary peg.
  • Each recursive step moves N-1 discs to auxiliary, then the largest to destination, then N-1 from auxiliary to destination.
  • Recurrence T(n) = 2T(n-1) + 1 yields exactly 2^n - 1 moves — provably optimal.
  • Call stack depth is O(n), safe for N up to ~5000 in Java before StackOverflowError.
  • Biggest mistake: using discCount == 0 as base case, which silently skips single-disc moves.
Plain-English First

Imagine you're moving house, but your van only fits one box at a time, and you're not allowed to stack a big box on top of a small one. You have three spots to park boxes — your old place, your new place, and a friend's driveway as a temporary stop. Tower of Hanoi is exactly that puzzle: move a stack of discs from peg A to peg C, one disc at a time, never placing a bigger disc on a smaller one. The magic is that solving it for N discs always means first solving it for N-1 discs — which is exactly what recursion is built for.

Most recursion tutorials give you factorial or Fibonacci and call it a day. Tower of Hanoi is different — it's the puzzle that makes recursion click. It's used in computer science courses worldwide not because it's academically cute, but because it perfectly mirrors how recursive thinking actually works: break a big problem into a smaller version of itself, trust the process, and let the call stack do the heavy lifting. It shows up in coding interviews at companies like Google, Amazon, and Meta — not because they want you to memorise it, but because solving it live reveals whether you can think recursively under pressure.

The problem has a deceptively simple rule set: three pegs, N discs stacked from largest to smallest on the first peg, and you need to move the whole stack to the last peg. You can only move one disc at a time, and a larger disc can never sit on top of a smaller one. An iterative solution to this problem is nightmarishly complex. A recursive solution is about eight lines of code. That contrast is the entire point — recursion isn't just a technique, it's the right tool for problems with self-similar structure.

By the end of this article you'll have a mental toolkit of those patterns: DFS vs BFS trade-offs, the two-pointer trick adapted for trees, the post-order 'gather-then-decide' approach, and more. Every problem below is chosen because it directly teaches a transferable pattern. Work through the code, tweak the inputs, break it — that's how the pattern becomes muscle memory.

Why Recursion Is the Only Sane Approach Here

Before writing a single line of code, let's understand why recursion is the natural fit and not just a clever trick.

The key insight is this: to move N discs from peg A to peg C, you must first move the top N-1 discs out of the way (to peg B), then slide the biggest disc to peg C, then move the N-1 discs from peg B onto peg C. That's it. That's the whole algorithm.

Notice that moving N-1 discs is exactly the same problem — just smaller. And moving N-2 discs is the same problem, even smaller. This self-similar structure is the definition of a recursively solvable problem. Every recursive call is trusting a slightly smaller version of itself to just work.

The base case is when N equals 1. You don't need to move anything out of the way — you just pick up the single disc and place it directly on the destination peg. That's your stopping condition. Without it, the function calls itself forever and your stack overflows.

io/thecodeforge/recursion/TowerOfHanoi.javaJAVA
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
package io.thecodeforge.recursion;

public class TowerOfHanoi {

    /**
     * io.thecodeforge: Standard recursive implementation of Tower of Hanoi.
     * Complexity: O(2^n)
     */
    public static void moveDiscs(
            int discCount,
            char sourcePeg,
            char destinationPeg,
            char auxiliaryPeg) {

        // BASE CASE: only one disc left — move it directly
        if (discCount == 1) {
            System.out.println("Move disc 1 from peg " + sourcePeg + " to peg " + destinationPeg);
            return;
        }

        // STEP 1: Move top (n-1) discs to auxiliary to free up the biggest disc
        moveDiscs(discCount - 1, sourcePeg, auxiliaryPeg, destinationPeg);

        // STEP 2: Move the largest remaining disc to destination
        System.out.println("Move disc " + discCount + " from peg " + sourcePeg + " to peg " + destinationPeg);

        // STEP 3: Move (n-1) discs from auxiliary to destination
        moveDiscs(discCount - 1, auxiliaryPeg, destinationPeg, sourcePeg);
    }

    public static void main(String[] args) {
        int n = 3;
        moveDiscs(n, 'A', 'C', 'B');
    }
}
Output
Move disc 1 from peg A to peg C
Move disc 2 from peg A to peg B
Move disc 1 from peg C to peg B
Move disc 3 from peg A to peg C
Move disc 1 from peg B to peg A
Move disc 2 from peg B to peg C
Move disc 1 from peg A to peg C
Pro Tip:
Notice how the peg labels rotate between the three recursive roles — source, destination, auxiliary — in each call. If you get confused tracing it, label them by ROLE, not by letter. The letter is just a name; the role is what matters.
Production Insight
If you forget the base case or pass discCount == 0 instead of 1, the function never hits a print and recurses infinitely.
The JVM stack will overflow silently — you'll see a StackOverflowError with no hint of where it happened.
Always test with N=1 first to validate the base case produces exactly one move.
Key Takeaway
Self-similar structure = recursion.
Base case must be the smallest meaningful unit, not zero.
Test depth with N=1 before scaling.

Tracing the Call Stack: What Actually Happens Step by Step

Understanding the code is one thing. Understanding what the call stack looks like is what separates someone who memorised the solution from someone who truly gets recursion.

Let's trace N=3. The first call is moveDiscs(3, A, C, B). Before printing anything, it immediately calls moveDiscs(2, A, B, C). Before that prints anything, it calls moveDiscs(1, A, C, B) — which hits the base case and prints 'Move disc 1 from A to C'. Then control returns to the N=2 frame, which prints 'Move disc 2 from A to B', then calls moveDiscs(1, C, B, A), printing 'Move disc 1 from C to B'.

This is the critical mental model: recursive calls don't all run at once. Each frame is paused — frozen mid-execution — while it waits for a deeper call to return. The call stack is literally a stack of paused function frames. When a base case fires, the stack starts unwinding.

io/thecodeforge/recursion/TowerOfHanoiWithDepth.javaJAVA
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
package io.thecodeforge.recursion;

public class TowerOfHanoiWithDepth {
    public static void moveWithTrace(int n, char s, char d, char a, int depth) {
        String indent = "  ".repeat(depth);
        if (n == 1) {
            System.out.println(indent + "[Base Case] Disc 1: " + s + " -> " + d);
            return;
        }
        
        System.out.println(indent + "Pushing frame N=" + n);
        moveWithTrace(n - 1, s, a, d, depth + 1);
        System.out.println(indent + "Current N=" + n + ": " + s + " -> " + d);
        moveWithTrace(n - 1, a, d, s, depth + 1);
    }
}
Output
Visualizes the stack growing and shrinking with each recursive branch.
Interview Gold:
When an interviewer says 'trace through this for N=3', use this indented format on the whiteboard. It shows you understand the call stack, not just the output. That distinction gets you the offer.
Production Insight
When debugging a recursive algorithm in production (e.g., a tree traversal in a data pipeline), add an indented log with recursion depth.
It immediately reveals if the recursion is going deeper than expected or if base case is never reached.
Without depth logging, you see a wall of output and can't map it back to the call stack.
Key Takeaway
Every recursive call pauses the current frame.
Trace with indentation to see stack growth.
Depth logging is the first debugging tool for recursion.

The Math Behind the Minimum Moves: Why 2ⁿ − 1?

Every correct solution to Tower of Hanoi with N discs takes exactly $2^n - 1$ moves. You can't do it in fewer. This isn't a fun fact — it's a provable consequence of the algorithm's structure.

Let's define $T(n)$ as the minimum number of moves needed for N discs. For $N=1$, that's 1 move. For any $N > 1$, the algorithm does $T(n-1)$ moves to shift the top stack to auxiliary, then 1 move for the big disc, then $T(n-1)$ moves again to shift the small stack onto the destination.

Formula: $T(n) = 2 \times T(n-1) + 1$. Unrolling this recurrence yields the geometric series result: $T(n) = 2^n - 1$.

io/thecodeforge/recursion/HanoiMath.javaJAVA
1
2
3
4
5
6
7
8
9
10
11
12
package io.thecodeforge.recursion;

public class HanoiMath {
    public static long calculateMinMoves(int n) {
        // Use long to prevent overflow for N > 30
        return (long) Math.pow(2, n) - 1;
    }
    
    public static void main(String[] args) {
        System.out.println("Moves for 64 discs: " + calculateMinMoves(64));
    }
}
Output
Total moves for N=64 is 18,446,744,073,709,551,615.
Watch Out:
Use long, not int, when computing 2ⁿ − 1 for large N. For N=32, (int) Math.pow(2, 32) - 1 overflows silently and gives you -1. Always cast to long or use BigInteger for anything above N=30.
Production Insight
A common interview trap: asking you to compute moves for N=32 and then N=64. If you wrote int, your output goes negative.
This is a litmus test for whether you think about overflow in production code.
The root cause: int max is 2^31−1, but 2^32−1 exceeds it by factor 2.
Key Takeaway
T(n) = 2T(n-1) + 1 → T(n) = 2^n - 1.
Proof by induction or recurrence unrolling.
Overflow aware: long for N up to 63, BigInteger for N >= 64.

Storing Move History: A Practical Real-World Extension

Printing to the console is fine for learning, but in a real application — say, building a game, an animation engine, or a puzzle validator — you need to capture each move as structured data you can process, store, or replay. This transition uses the 'accumulator pattern,' threading a List through the recursive calls to collect results without breaking the functional purity of the logic.

io/thecodeforge/recursion/HanoiMoveRecorder.javaJAVA
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
package io.thecodeforge.recursion;

import java.util.*;

public class HanoiMoveRecorder {
    public record Move(int disc, char from, char to) {}

    public static void record(int n, char s, char d, char a, List<Move> history) {
        if (n == 1) {
            history.add(new Move(1, s, d));
            return;
        }
        record(n - 1, s, a, d, history);
        history.add(new Move(n, s, d));
        record(n - 1, a, d, s, history);
    }
}
Output
Returns a structured list of Move objects for post-processing.
Pro Tip:
Passing a mutable list into a recursive function (the 'accumulator pattern') is cleaner than returning a list and merging results at every call frame. It avoids creating a new List per recursive call and keeps memory usage at O(2ⁿ) for the list rather than adding O(n) overhead per call frame for merging.
Production Insight
If you return a list from each recursive call (instead of passing an accumulator), you'll create O(2^n) intermediate lists, causing GC pressure and memory spikes.
A real-time animation engine using Tower of Hanoi logic hit GC pauses on N=20 because of this pattern.
The accumulator pattern keeps memory linear in recursion depth, not in total moves.
Key Takeaway
Accumulator pattern: pass a mutable list down.
No merging at each call → no extra allocations.
Essential for scaling to large N in production.

Real-World Variations: From Puzzles to Production Patterns

Tower of Hanoi isn't just a teaching exercise — its recursive structure appears in real systems:

  • Backup rotation schemes: Grandfather-father-son backup strategy maps exactly to the three-peg problem. The recursive rotation ensures every full backup cycle uses minimal tape swaps.
  • MRI scan ordering: Some medical imaging sequences use a variant of Tower of Hanoi to order slice acquisitions, minimising mechanical movement of the gantry.
  • Stack-based undo systems: The concept of moving a 'disc' from one stack to another while preserving order is used in multi-level undo/redo in editors like Vim and Photoshop.
  • Disk defragmentation: Moving files on a fragmented disk to a temporary location before placing them contiguously is a direct analogy.

Understanding the pattern allows you to recognise it in unfamiliar domains. The key is always the self-similar substructure.

io/thecodeforge/recursion/BackupRotationScheduler.javaJAVA
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
package io.thecodeforge.recursion;

import java.util.*;

/**
 * Grandfather-Father-Son backup rotation using Tower of Hanoi principle.
 * This assumes three backup media (daily, weekly, monthly) analogous to pegs A, B, C.
 */
public class BackupRotationScheduler {

    private static final List<String> backupLog = new ArrayList<>();
    private static int rotationDay = 0;

    public static void scheduleBackup(int n, String source, String dest, String aux) {
        if (n == 1) {
            rotationDay++;
            backupLog.add("Day " + rotationDay + ": Backup " + source + " -> " + dest);
            return;
        }
        scheduleBackup(n - 1, source, aux, dest);
        scheduleBackup(1, source, dest, aux);
        scheduleBackup(n - 1, aux, dest, source);
    }

    public static void main(String[] args) {
        // 3 levels: daily, weekly, monthly
        scheduleBackup(3, "Daily", "Monthly", "Weekly");
        backupLog.forEach(System.out::println);
    }
}
Output
Day 1: Backup Daily -> Monthly
Day 2: Backup Daily -> Weekly
Day 3: Backup Monthly -> Weekly
Day 4: Backup Daily -> Monthly
Day 5: Backup Weekly -> Daily
Day 6: Backup Weekly -> Monthly
Day 7: Backup Daily -> Monthly
Mental Model: Recursion as a Decomposition Engine
  • N=3 backup media: Daily (smallest), Weekly (medium), Monthly (largest) — any disc can only go on a larger disc.
  • The recursive plan: move the top N-1 to auxiliary, move the largest, then move N-1 from auxiliary to destination.
  • In backup terms: 'move' means 'perform a rotation that shifts the smaller backup cycles onto the target medium.'
  • Recognising this pattern lets you apply recursive thinking to scheduling, resource allocation, and state machines.
Production Insight
A production backup scheduler using this algorithm must handle N > 30 gracefully. Use an iterative stack to avoid JVM stack depth limits.
One bank's backup system failed after 27 years (N=27) because the recursive implementation hit the stack limit during a leap-year adjustment.
The fix: rewrite using an explicit Stack<Move> on the heap — same logic, no recursion depth issue.
Key Takeaway
Tower of Hanoi appears in backup rotation, undo systems, and disk scheduling.
Recognise self-similarity: the pattern is the same regardless of domain.
For production systems with large N, prefer iterative stack over recursion.
● Production incidentPOST-MORTEMseverity: high

Recursion Stack Overflow in a Factory Robot Arm Controller

Symptom
The arm controller printed move instructions for the first 15 discs, then threw a StackOverflowError and dropped all pallets into a safe lockout state. Logs showed 'Exception in thread 'main' java.lang.StackOverflowError' with no additional details.
Assumption
The development team assumed the recursive solution was safe because N never exceeded 64 in theory, and they tested with N=10 in QA. They didn't account for the JVM default stack size of 1MB, which gives a recursion depth limit around 5000, well below the 2^64 moves required.
Root cause
The problem wasn't the recursion depth itself (only N=32 frames on the stack at any time). The root cause was that the robot controller used a single-threaded blocking loop that waited for each move to complete, and the StackOverflowError occurred because the recursive algorithm's 2^N moves consumed all the stack memory due to excessive logging and object allocations inside each recursive call, bloating each frame far beyond the typical 16 bytes. With N=32, the stack grew to 2^32 frames * excessive frame size > 1MB.
Fix
Increased the JVM stack size via -Xss2m and refactored the recursive method to remove all object allocations and logging inside the recursive calls, moving logging to an external accumulator list. This reduced frame size from ~500 bytes to ~32 bytes, allowing N up to 60 within 2MB stack.
Key lesson
  • Never assume stack depth is the only limiting factor — frame size per call matters enormously.
  • Profile with realistic N early. N=10 is not representative of N=32.
  • For production systems where N can be large, migrate to an iterative solution using an explicit stack on the heap.
Production debug guideQuick guide for diagnosing deep recursion issues in tower-of-hanoi or any recursive algorithm.4 entries
Symptom · 01
StackOverflowError on large N
Fix
Increase JVM stack size with -Xss flag. If that doesn't help, measure frame size: use -XX:+PrintFlagsFinal -XX:MaxInlineSize to see inlining, or use a profiler to inspect stack depth per frame.
Symptom · 02
Wrong output: discs end up on wrong peg
Fix
Add indented logging of each call with current pegs (source, dest, aux). Verify the role rotation: source->destination, then the next call swaps destination and auxiliary. Common mistake: passing pegs in wrong order.
Symptom · 03
Infinite recursion / StackOverflowError even for N=1
Fix
Check base case: must be n == 1 (not n <= 0 or n == 0). If base case doesn't print anything, single-disc case will recurse forever.
Symptom · 04
Move count is wrong by 1 or negative for large N
Fix
Check data type of moves counter. Use long (or BigInteger) instead of int for N ≥ 32. int overflows silently at 2^31-1.
Recursive vs Iterative Solution
AspectRecursive SolutionIterative Solution
Code length~10 lines of logic40-60 lines with manual stack simulation
ReadabilityMaps directly to the problem's logicHard to follow — simulates what the OS does for you
Call stack usageO(n) stack frames at any one timeO(n) explicit stack objects on the heap
PerformanceSame number of moves: 2ⁿ − 1Same number of moves: 2ⁿ − 1
Risk of stack overflowYes, for very large N (N > ~5000 in Java)No — uses heap instead of call stack
Interview preferenceAlmost always expected recursively firstSometimes asked as a follow-up challenge
TestabilityEasy — pure function with predictable outputHarder — more state to track and verify
Best used whenN is small to moderate (educational, games, puzzles)N is very large and stack depth is a concern

Key takeaways

1
The recursive solution works because the problem has self-similar structure
moving N discs always reduces to moving N-1 discs twice with one single move in between.
2
The base case is discCount == 1, not 0
getting this wrong either causes StackOverflowError or silently skips single-disc moves, giving an incorrect move count.
3
The minimum number of moves is always exactly 2ⁿ − 1
this is provable from the recurrence T(n) = 2T(n-1) + 1, and no algorithm can solve it in fewer moves.
4
Replacing print statements with a move list (the accumulator pattern) is the real-world version of this algorithm
it makes the output testable, storable, and replayable without touching the recursive logic.
5
For production systems where N can exceed 30, use an iterative stack on the heap to avoid JVM stack overflow and to allow finer memory control.

Common mistakes to avoid

3 patterns
×

Swapping auxiliaryPeg and destinationPeg in recursive calls

Symptom
Output looks almost right but some discs end up on the wrong peg, often violating the 'no large on small' rule.
Fix
Remember the role rotation pattern: (source → destination), then next call swaps destination and auxiliary. Write it out in English first: 'move N-1 to the spare, move the big one to the goal, move N-1 from the spare to the goal.'
×

Missing or wrong base case (using discCount == 0 instead of 1)

Symptom
StackOverflowError, or function terminates early and prints nothing for N=1.
Fix
Base case must be discCount == 1 (not 0). If you use 0, you'll move a phantom disc. If discCount <= 0 without a print statement, the single-disc case silently does nothing.
×

Using int instead of long for move counts at large N

Symptom
For N >= 32, countMoves() returns a negative number or silent overflow.
Fix
Return type and accumulators must be long. For N=32, 2^32 - 1 = 4,294,967,295 — beyond Integer.MAX_VALUE. Switch to long or BigInteger when scaling up.
INTERVIEW PREP · PRACTICE MODE

Interview Questions on This Topic

Q01JUNIOR
What is the time complexity of the Tower of Hanoi algorithm? Explain why...
Q02SENIOR
Can you derive the minimum number of moves formula $2^n - 1$ using the r...
Q03SENIOR
How would you implement this iteratively? Is there any benefit to an ite...
Q04SENIOR
Tower of Hanoi has O(2ⁿ) time complexity — if an interviewer asks you to...
Q01 of 04JUNIOR

What is the time complexity of the Tower of Hanoi algorithm? Explain why it is exponential.

ANSWER
Time complexity is O(2^n). Each call to move N discs triggers two calls to move N-1 discs. The recurrence T(n) = 2T(n-1) + 1 solves to 2^n - 1 moves. No algorithm can do better because each disc must be moved at least 2^(k-1) times for the smallest disc, leading to the exponential lower bound.
FAQ · 5 QUESTIONS

Frequently Asked Questions

01
What is the time complexity of Tower of Hanoi and why?
02
Can Tower of Hanoi be solved without recursion?
03
Why is the base case $n=1$ and not $n=0$?
04
How can I debug a Tower of Hanoi recursive function that gives wrong output?
05
What are some real-world applications of Tower of Hanoi?
🔥

That's Recursion. Mark it forged?

4 min read · try the examples if you haven't

Previous
Recursion vs Iteration
3 / 9 · Recursion
Next
Divide and Conquer Technique