Bootcamps
Masterclasses
Menu
Courses
Account
Login / Sign Up

Tower of Hanoi

Medium Acceptance 35.23% Points 30

In the Tower of Hanoi puzzle, you are given n disks arranged in ascending order (with the smallest disk on top) on the first of three rods. The objective is to move all the disks to the third rod while adhering to the following two rules: only one disk can be moved at a time, and no disk may be placed on top of a smaller disk. Given the number of disks n and the three rods labeled as "from" (the starting rod), "to" (the target rod), and "aux" (the auxiliary rod), the task is to calculate the total number of moves required to transfer all the disks from the starting rod to the target rod.

Examples
Example 1

Example 1

Input: n = 3

Output: 7

Explanation: For n = 3, the steps are as follows: Move disk 1 from rod 1 to rod 3. Move disk 2 from rod 1 to rod 2. Move disk 1 from rod 3 to rod 2. Move disk 3 from rod 1 to rod 3. Move disk 1 from rod 2 to rod 1. Move disk 2 from rod 2 to rod 3. Move disk 1 from rod 1 to rod 3

Example 2

Example 2

Input: n = 0

Output: 0

Explanation: Total 0 steps will be taken.

Constraints
  • 0 <= n <= 16
Hints
  • Expected Time Complexity: O(2^n)
  • Expected Auxiliary Space: O(n)
Topics
Recursion
Companies
Microsoft Flipkart
Added 28 Dec 2024 35.23% acceptance
Ln 1, Col 1Sign in to save your code
0
0