Tower of Hanoi recursive algorithm explained: 3-peg rules, move recurrence relation (2ⁿ - 1), divide-and-conquer strategy, and JavaScript implementation.
Tower of Hanoi is a mathematical puzzle consisting of three pegs and N disks of different sizes. The objective is to move the entire stack from the source peg to the destination peg, respecting two rules: only one disk can be moved at a time, and no larger disk may be placed on top of a smaller disk.
It is a pure example of divide-and-conquer recursion requiring exactly 2ⁿ - 1 moves for n disks.
Recursively transfer N-1 smaller disks from Source peg to Auxiliary peg using Target peg as temporary buffer.
Move the single remaining largest disk (disk N) directly from Source peg to Target peg.
Recursively transfer the N-1 disks from Auxiliary peg to Target peg using Source peg as temporary buffer.
For a single disk, directly move it from Source to Target peg without further recursion.
1function hanoi(n, source, target, auxiliary, moves = []) {2 if (n === 1) {3 moves.push(`Move disk 1 from ${source} to ${target}`);4 return moves;5 }6 7 // Step 1: Move n-1 disks from source to auxiliary8 hanoi(n - 1, source, auxiliary, target, moves);9 10 // Step 2: Move the nth disk from source to target11 moves.push(`Move disk ${n} from ${source} to ${target}`);12 13 // Step 3: Move n-1 disks from auxiliary to target14 hanoi(n - 1, auxiliary, target, source, moves);15 16 return moves;17}18 19// Example usage:20// hanoi(3, 'Peg A', 'Peg C', 'Peg B');21// Total moves: 2³ - 1 = 7 movesPlay through every comparison, swap, and state change, adjust the speed, or enter custom inputs to test edge cases.
The full interactive roadmap is unlocking — these specialized modules land in upcoming releases.
This feature will be implemented in the next update.
This feature will be implemented in the next update.
This feature will be implemented in the next update.
Explore the full catalog — 30+ algorithms with more unlocking every release.
Recursion stack & backtracking exploration animator
Test your understanding of Tower of Hanoi complexity and step mechanics.
Q1.What is the minimum number of moves required to solve Tower of Hanoi for 4 disks?
Q2.What is the maximum recursion depth (call stack space complexity) for solving Tower of Hanoi with n disks?
Apply Tower of Hanoi to real coding interview questions.
Print all step-by-step disk moves and total move count for N disks.