🏯 Tower of Hanoi: Recursive Logic & Hardware Realities

This project is a visual and mathematical exploration of the Tower of Hanoi algorithm, featured on the Bug and Code LLC YouTube Channel.

Tower of Hanoi Logic Breakdown

🚀 Launch the Live Interactive Engine


🧠 Mechanics of the Algorithm: Tearing Down Recursion

The Tower of Hanoi is the quintessential recursive problem. But recursion isn't magic—it is a series of execution context frames stacked sequentially in system memory.

To move $n$ physical disks from a Source peg to a Target peg using an Auxiliary peg without violating stack order (never putting a larger block on a smaller one), the execution flow breaks down into three distinct operational phases:

  1. Phase 1 (Isolate): Move the top $n-1$ disks from the Source peg to the Auxiliary peg.
  2. Phase 2 (Execute): Shift the largest remaining structural disk ($n$) directly from Source to Target.
  3. Phase 3 (Reassemble): Move the $n-1$ waiting disks from the Auxiliary peg to the Target peg.

Tower of Hanoi Logic Breakdown


🔢 The Mathematical Reality: $2^n - 1$ Space Complexity

Every single structural disk added to the array exactly doubles the computational execution length of the algorithm. This isn't abstract; it represents a hard recurrence relation:

$$T(n) = 2T(n-1) + 1$$

When resolved, the mathematical minimum threshold of operational steps scales exponentially at exactly $2^n - 1$. If you increase your input bounds linearly, your execution time scales brutally.

Input Disks ($n$) Algorithmic Execution Vector ($2^n - 1$) Total Hardware Moves Required
3 $2^3 - 1$ 7
4 $2^4 - 1$ 15
5 $2^5 - 1$ 31

Mathematical Pattern Visualization


💻 Cleanroom Code Implementation

The beauty of recursion is how clean the abstraction looks in source code, despite the massive branching work it forces the underlying CPU call stack to handle.

Here is the implementation written with zero dependencies, raw variable mappings, and pure logic:


/**
 * Executes the exponential Tower of Hanoi shift matrix.
 * * @param {number} n - Total structural units (disks)
 * @param {string} source - Origin memory array identifier
 * @param {string} helper - Auxiliary overflow layout identifier
 * @param {string} target - Ultimate execution destination identifier
 */
function hanoi(n, source, helper, target) {
  // Base Case: Once memory depth drops below operational limits, halt stack growth
  if (n <= 0) return;

  // Phase 1: Clear the workspace. Move n-1 items to the auxiliary layout.
  hanoi(n - 1, source, target, helper);

  // Phase 2: Core Action. Register the definitive physical move.
  console.log(`Move disk ${n}: ${source} -> ${target}`);

  // Phase 3: Final Consolidation. Shift the n-1 units over to the target workspace.
  hanoi(n - 1, helper, source, target);
}