Data Structures & AlgorithmsEasyAccenture · Cognizant coding round pattern

Problem: Tower of Hanoi: move n disks from peg A to peg C using B, recording every move.

Problem: Tower of Hanoi: move n disks from peg A to peg C using B, recording every move.
moves = []
def hanoi(n, a, b, c):
    if n == 0: return
    hanoi(n - 1, a, c, b)
    moves.append((a, c))
    hanoi(n - 1, b, a, c)
hanoi(4, "A", "B", "C")
print(len(moves), moves[0], moves[7])
What is printed?
  1. A. 15 ('A', 'B') ('A', 'C')
  2. B. 15 ('A', 'B') ('B', 'C')
  3. C. 16 ('A', 'B') ('A', 'C')
  4. D. 15 ('A', 'C') ('A', 'C')

Correct answer: A. 15 ('A', 'B') ('A', 'C')

T(n) = 2T(n − 1) + 1 = 2ⁿ − 1 = 15 moves for 4 disks. With an even number of disks the first move goes A → B (the smallest disk heads for the spare peg). Move index 7 is the middle move – the largest disk going A → C – after the top 3 disks (7 moves) are parked on B. O(2ⁿ).

More Coding Interview Problems questions

Exams that ask this topic