Tower of Hanoi Problem in DSA Javascript - Time & Space Complexity
We want to understand how the number of moves grows as we increase the number of disks in the Tower of Hanoi problem.
How does the work needed change when we add more disks?
Analyze the time complexity of the recursive Tower of Hanoi solution below.
function towerOfHanoi(n, from, to, aux) {
if (n === 1) {
console.log(`Move disk 1 from ${from} to ${to}`);
return;
}
towerOfHanoi(n - 1, from, aux, to);
console.log(`Move disk ${n} from ${from} to ${to}`);
towerOfHanoi(n - 1, aux, to, from);
}
This code moves n disks from one peg to another using recursion and an auxiliary peg.
Look at the recursive calls that repeat the same process for smaller numbers of disks.
- Primary operation: Recursive calls to move smaller stacks of disks.
- How many times: Each call makes two recursive calls with n-1 disks plus one move operation.
Each time we add a disk, the number of moves roughly doubles and then adds one more move.
| Input Size (n) | Approx. Operations (Moves) |
|---|---|
| 1 | 1 |
| 2 | 3 |
| 3 | 7 |
| 4 | 15 |
| 5 | 31 |
Pattern observation: The moves grow exponentially, doubling each time plus one extra move.
Time Complexity: O(2n)
This means the number of moves grows very fast as we add more disks, doubling roughly with each extra disk.
[X] Wrong: "The time grows linearly with the number of disks because we just move each disk once."
[OK] Correct: Actually, disks are moved multiple times in a specific order, so the total moves grow exponentially, not just once per disk.
Understanding this problem helps you think about recursion and exponential growth, which are common in many coding challenges.
"What if we changed the problem to move disks iteratively instead of recursively? How would the time complexity change?"
Practice
Solution
Step 1: Understand the formula for minimum moves
The minimum moves required for n disks is 2^n - 1.Step 2: Calculate for 3 disks
For 3 disks, minimum moves = 2^3 - 1 = 8 - 1 = 7.Final Answer:
7 -> Option AQuick Check:
2^3 - 1 = 7 [OK]
- Forgetting to subtract 1
- Using n instead of 2^n - 1
- Confusing number of disks with moves
Solution
Step 1: Identify base case for recursion
The recursion stops when there are no disks to move, i.e., n === 0.Step 2: Check the options
if (n === 0) return; correctly returns when n is 0, stopping recursion.Final Answer:
if (n === 0) return; -> Option DQuick Check:
Base case is n === 0 [OK]
- Using n === 1 as base case incorrectly
- Not stopping recursion causing infinite calls
- Using invalid conditions like n < 0
function towerOfHanoi(n, from, to, aux) {
if (n === 0) return;
towerOfHanoi(n - 1, from, aux, to);
console.log(`Move disk ${n} from ${from} to ${to}`);
towerOfHanoi(n - 1, aux, to, from);
}
towerOfHanoi(2, 'A', 'C', 'B');Solution
Step 1: Trace recursive calls for n=2
First move disk 1 from A to B, then disk 2 from A to C, then disk 1 from B to C.Step 2: Match output with options
"Move disk 1 from A to B" "Move disk 2 from A to C" "Move disk 1 from B to C" matches the exact sequence of moves printed by the code.Final Answer:
"Move disk 1 from A to B" "Move disk 2 from A to C" "Move disk 1 from B to C" -> Option CQuick Check:
Correct move sequence for 2 disks = "Move disk 1 from A to B" "Move disk 2 from A to C" "Move disk 1 from B to C" [OK]
- Mixing source and auxiliary rods
- Confusing disk numbers in moves
- Ignoring order of recursive calls
function towerOfHanoi(n, from, to, aux) {
if (n === 1) {
console.log(`Move disk 1 from ${from} to ${to}`);
return;
}
towerOfHanoi(n - 1, from, to, aux);
console.log(`Move disk ${n} from ${from} to ${to}`);
towerOfHanoi(n - 1, aux, to, from);
}Solution
Step 1: Analyze recursive calls
The first recursive call should move n-1 disks from 'from' to 'aux' using 'to' as auxiliary, but here 'to' and 'aux' are swapped.Step 2: Correct the argument order
Swapping 'to' and 'aux' in the first recursive call fixes the logic to move disks correctly.Final Answer:
Swap 'to' and 'aux' in the first recursive call -> Option AQuick Check:
Correct recursive call order fixes error [OK]
- Mixing auxiliary and target rods
- Incorrect base case causing infinite recursion
- Removing necessary recursive calls
function towerOfHanoi(n, from, to, aux) {
if (n === 0) return;
towerOfHanoi(n - 1, from, aux, to);
console.log(`Move disk ${n} from ${from} to ${to}`);
towerOfHanoi(n - 1, aux, to, from);
}Solution
Step 1: Understand the requirement
We want to print moves only when disk 1 moves, but still perform all recursive calls to solve the problem.Step 2: Modify print statement with condition
Add an if condition to print only when n === 1, so other moves are not printed but recursion continues.Final Answer:
Add an if condition to print only when n === 1 inside the function -> Option BQuick Check:
Conditional print inside recursion solves problem [OK]
- Changing base case breaks recursion
- Removing recursive calls stops solution
- Filtering output outside misses recursion logic
Ready to prove it?
Pass the test and this pattern moves unknown
