# Time Complexity Analysis | Tower Of Hanoi (Recursion)

• Difficulty Level : Medium
• Last Updated : 22 Jan, 2021

Tower of Hanoi is a mathematical puzzle where we have three rods and n disks. The objective of the puzzle is to move the entire stack to another rod, obeying the following simple rules:
1) Only one disk can be moved at a time.
2) Each move consists of taking the upper disk from one of the stacks and placing it on top of another stack i.e. a disk can only be moved if it is the uppermost disk on a stack.
3) No disk may be placed on top of a smaller disk.

Pseudo Code

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.

```TOH(n, x, y, z)
{
if (n >= 1)
{
// put (n-1) disk to z by using y
TOH((n-1), x, z, y)

// move larger disk to right place
move:x-->y

// put (n-1) disk to right place
TOH((n-1), z, y, x)
}
}```

Analysis of Recursion

Recursive Equation : ——-equation-1

Solving it by Backsubstitution : ———–equation-2 ———–equation-3

Put the value of T(n-2) in the equation–2 with help of equation-3 ——equation-4

Put the value of T(n-1) in equation-1 with help of equation-4  After Generalization : Base condition T(1) =1
n – k = 1
k = n-1
put, k = n-1 It is a GP series, and the sum is  , or you can say which is exponential

for 5 disks i.e. n=5 It will take 2^5-1=31 moves.

My Personal Notes arrow_drop_up