You are on page 1of 2

3) Describe a recursive algorithm for the case k = n + 1:

Ans:

Steps:

leftEmpty = 1, shift = k-1, right = k.

(Note: Starting index is 1 for both k and n)

1) Move Smallest disk to the right most peg (at index right ). Similarly, 2 nd smallest disk to 2nd
right most peg and so on...

Total no. of moves: n + n-1 + … + 1

2) Move the right most disk to the left most empty (at index leftEmpty) peg. And increase the
leftEmpty = leftEmpty + 1.

Total no. of moves: n + n-1 + … + 2

3) Right shift every disk by 1 peg which are at index leftEmpty+1 to shift (start shifting from
right side).

Total no. of moves: n-1 + n-2 + … + 1

4) Repeat step 2 & 3 until right most peg contains largest disk.
5) Now start moving disk from right side (start from the second right most disk) to the right
most(destination) peg.

Total no. of moves: n + n-1 + … + 2

Time Complexity:

n(n+1)/2 + (n(n+1)/2 – 1) + n(n-1)/2 + (n(n+1)/2 – 1)

(n^2 + n + n^2 + n -2 + n^2 – n + n^2 + n – 2) / 2

4(n^2) + 2n – 4 / 2

2(n^2) + n - 2

O(n^2)
2)

Steps:

(Note: Starting index is 1 for both k and n)

leftEmpty = 1, shift = k-1, right = k.

1) Move Smallest disk to the right most peg (at index right ). Similarly, 2 nd smallest disk to 2nd
right most peg and so on...

Total no. of moves: (1+ 2 + … + n-1 + n) + (1 + 2 + … + n-1) + … + 1

2) Now move all disks(Except largest) starting from 2 nd largest to the 1st peg.
Total no. of moves: (2 + … + n-1 + n) + (2 + … + n-1) + … 2

3) Now Shift the next largest disk to the Destination(k th) peg.
Total no. of moves: (n-1) + (n-1) + …(n-1)times

4) Repeat steps 1,2 & 3 until right most peg have n-1 disks.
5) Move 1st(Smallest) disk to the right most(destination) peg.

Total no. of moves: n

You might also like