Tower of Hanoi - Problem

The Tower of Hanoi is a classic puzzle consisting of three rods and a number of disks of different sizes which can slide onto any rod. The puzzle starts with all disks stacked on one rod in ascending order of size (smallest on top).

The objective is to move the entire stack to another rod, following these rules:

  • Only one disk can be moved at a time
  • Each move consists of taking the upper disk from one of the stacks and placing it on top of another stack
  • No disk may be placed on top of a smaller disk

Given n disks, print each move in the format "Move disk from [source] to [destination]" and return the total number of moves required.

Input & Output

Example 1 — Basic Case (n=3)
$ Input: n = 3
Output: Move disk 1 from A to C Move disk 2 from A to B Move disk 1 from C to B Move disk 3 from A to C Move disk 1 from B to A Move disk 2 from B to C Move disk 1 from A to C 7
💡 Note: To move 3 disks from A to C: first move disks 1,2 to B (3 moves), then disk 3 to C (1 move), then disks 1,2 from B to C (3 moves). Total: 7 moves.
Example 2 — Minimum Case (n=1)
$ Input: n = 1
Output: Move disk 1 from A to C 1
💡 Note: Only one disk to move directly from source A to destination C. Total: 1 move.
Example 3 — Small Case (n=2)
$ Input: n = 2
Output: Move disk 1 from A to B Move disk 2 from A to C Move disk 1 from B to C 3
💡 Note: Move disk 1 to B, disk 2 to C, then disk 1 on top of disk 2. Total: 3 moves.

Constraints

  • 1 ≤ n ≤ 20
  • Output each move on a separate line
  • Return total number of moves as the last line

Visualization

Tap to expand
Tower of Hanoi: Recursive SolutionINPUTn = 3 disks123Rod ARod BRod CGoal: Move all disksfrom A to CALGORITHM STEPS1hanoi(2, A, B, C)Move top 2 disks to auxiliary2Move disk 3: A → CMove largest disk directly3hanoi(2, B, C, A)Move 2 disks to destinationRecursive PatternT(n) = 2×T(n-1) + 1T(1) = 1Solution: T(n) = 2ⁿ - 1Time: O(2ⁿ), Space: O(n)Recursion depth = n levelsRESULTMoves Sequence:Move disk 1 from A to CMove disk 2 from A to BMove disk 1 from C to BMove disk 3 from A to CMove disk 1 from B to AMove disk 2 from B to CMove disk 1 from A to C7Total moves: 2³ - 1 = 7Final: All on Rod CKey Insight:The recursive structure mirrors the problem: to move n disks, recursively move n-1 disksout of the way, move the largest, then recursively move n-1 disks to the destination.TutorialsPoint - Tower of Hanoi | Recursive Approach
Asked in
Google 15 Amazon 12 Microsoft 18 Facebook 8
32.0K Views
Medium Frequency
~15 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen