Live Batches
Masterclasses
Menu
Free Courses
Account
Login / Sign Up

Tower of Hanoi

Medium Acceptance 35.23% Points 30.00

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.

Hints
Hint 1
Expected Time Complexity: O(2^n)
Hint 2
Expected Auxiliary Space: O(n)
Constraints
  • 0 <= n <= 16
Companies
Microsoft Flipkart
Topics
Recursion
Solution.cs C#JavaPythonC++Javascript

Unlock the code editor

Sign in to write, run, and submit your solution against the full test suite.

  • Run code against sample & hidden test cases
  • Save submissions and track your streak
  • Compare with editorial & community solutions