Tower of Hanoi — Python Technical Interview Questions & Answers

Tower of Hanoi

Tower of Hanoi

  • Tower of Hanoi is a classic practice problem. State the rule, trace a tiny input, then code. Fibonacci: next = sum of last two. Second largest: watch duplicates. Hanoi: move n-1, biggest, n-1. Distance: sqrt((x2-x1)**2 + (y2-y1)**2).
  • For Tower of Hanoi: say the output for one small n before you write the loop. That is the exam.
  • Tower of Hanoi — output: A → B, A → C, B → C. Two disks, three moves.

Technical Interview Tip: Rule + one dry-run + then code.

Code Examples for Tower of Hanoi

Example

# Tower of Hanoi
def hanoi(n, a, b, c):
    if n == 0:
        return
    hanoi(n - 1, a, c, b)
    print(a, "→", c)
    hanoi(n - 1, b, a, c)
hanoi(2, "A", "B", "C")

Tower of Hanoi — output: A → B, A → C, B → C. Two disks, three moves.

How to Explain Tower of Hanoi to an Interviewer

Explain Tower of Hanoi as if you are teaching a junior — definition, then one tiny script.

Tower of Hanoi — know the rule. Tower of Hanoi — tiny trace first.

What does the example print, and why?

Tower of Hanoi — output: A → B, A → C, B → C

What mistake do freshers make with Tower of Hanoi?

Tower of Hanoi — edge cases (n=0, duplicates).