← Questions
Tower of Hanoi moves
0
I was asked this
No reports yet. Sign in to say where you were asked it.
A coding interview question asked in Apple's technical phone screen, last asked Mar 2026. It tests recursion.
n disks of different sizes are stacked on peg A, largest at the bottom. Pegs B and C are empty. Move one disk at a time and never put a larger disk on a smaller one. Return the shortest sequence of moves that transfers every disk from A to C.
Interface
Unless you agree on a different interface with the interviewer, assume:
-
hanoi(n: int) -> list[str]— each move is a string"X -> Y": take the top disk of pegXand put it on pegY.
Example
hanoi(0) -> []
hanoi(1) -> ["A -> C"]
hanoi(2) -> ["A -> B", "A -> C", "B -> C"]
hanoi(3) -> ["A -> C", "A -> B", "C -> B", "A -> C", "B -> A", "B -> C", "A -> C"]
Constraints
-
0 <= n <= 12. - The sequence must be valid and of minimum length.
Clarifying questions
- Return the moves or print them?
- Is the move format fixed?
- Should the function check its own output, or can I write that as a test?
What a strong answer covers
- The recursion: move
n-1disks fromAtoBusingC, move the largest disk toC, then moven-1disks fromBtoCusingA. - Why it takes
2^n - 1moves:T(n) = 2T(n-1) + 1, and why no shorter sequence exists (the largest disk must move at least once, and before and after that move the othern-1disks must each be shifted as a whole stack). - Time and output size
O(2^n); recursion depthO(n). - A checker that replays the moves on three stacks and asserts every move is legal and
Cends full.
Follow-ups
- Write it iteratively (the smallest disk moves every other step in a fixed cycle).
- Return only the
k-th move without generating the others. - With four pegs, how many moves do you need?
Where it's asked
- Apple · Technical phone screen · Last asked Mar 2026
What it tests
No official answer yet. Write yours on the right and run it.
Nothing published yet.
Sign in to submit your code; every attempt is kept here.
Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding
