← Questions

Tower of Hanoi moves

0
AppleCodingLast asked Mar 2026

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 peg X and put it on peg Y.

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-1 disks from A to B using C, move the largest disk to C, then move n-1 disks from B to C using A.
  • Why it takes 2^n - 1 moves: 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 other n-1 disks must each be shifted as a whole stack).
  • Time and output size O(2^n); recursion depth O(n).
  • A checker that replays the moves on three stacks and asserts every move is legal and C ends 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

recursion

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