KatInterview

Recursive Disk Transfer Between Three Pegs

Trees & GraphsModel answer
MediumModel answerTrees & Graphsrecursionalgorithm-designcomplexity-analysis

Last updated

Move n disks from one peg to another using a spare peg, one at a time, never placing a larger disk on a smaller one.

You have n disks of distinct sizes sitting on the first of three pegs, arranged with the largest at the bottom and the smallest on top. Your goal is to relocate the entire stack to a different peg.

Rules:

  • Transfer exactly one disk per move
  • A disk can only be placed on an empty peg or on top of a strictly larger disk
  • You have a third peg available as temporary storage

Task:

Implement a function that produces the complete sequence of moves needed to solve the puzzle. Each move should specify which peg to take from and which to place onto. After presenting your solution, analyze its time and space complexity and explain why the approach is correct.

Example:

For n = 3 disks initially on peg 1, targeting peg 3 with peg 2 as spare, one valid solution contains 7 moves that successfully relocate all disks while respecting the size constraint.

Hints

Hint 1

Think about what must happen before and after moving the bottom-most disk

Hint 2

The problem for n disks can be broken down into smaller instances with n-1 disks and different peg assignments

Hint 3

The number of moves follows the recurrence M(n) = 2·M(n-1) + 1 with M(0) = 0