TCS · Question 2
Tower of Hanoi Problem
Problem
Move n disks from source to destination using an auxiliary rod, following the rules.
Approach
Move n-1 aside, shift the largest, then move n-1 again.
Time O(2ⁿ)Space O(n)
How it works
- 1Move n-1 disks to the auxiliary rod.
- 2Move the largest disk to the destination.
- 3Move the n-1 stack on top of it.
Sample input / output
Input: n = 2, rods = A (src), B (aux), C (dst) Output: Move disk 1 from A to B Move disk 2 from A to C Move disk 1 from B to C
Constraints
1 <= n <= 20; 2^n - 1 moves.
Solution — read it, then walk it
Time O(2ⁿ)Space O(n)Branches 1Returns 2source · C++
Scroll sideways for wide charts — the view follows the active step.
- start / end
- statement
- condition
- loop
- returns
- definition
1/13
StartSTART
Interactive control-flow diagram and step-by-step code walkthrough.
Recommended resourcesAffiliate links · may earn us a commission
Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits