Data Structures & AlgorithmsHardProduct Company SDE · Amazon/Microsoft-style OA

Problem: Board game on squares 1..n: roll a die (1–6); landing on the foot of a ladder or the head of a snake moves you to its other end. Minimum rolls to reach square n (BFS).

Problem: Board game on squares 1..n: roll a die (1–6); landing on the foot of a ladder or the head of a snake moves you to its other end. Minimum rolls to reach square n (BFS).
from collections import deque
def board_moves(n, jumps):
    q = deque([(1, 0)]); seen = {1}
    while q:
        cell, d = q.popleft()
        if cell == n: return d
        for k in range(1, 7):
            nxt = cell + k
            if nxt > n: break
            nxt = jumps.get(nxt, nxt)
            if nxt not in seen: seen.add(nxt); q.append((nxt, d + 1))
    return -1
J = {3: 22, 5: 8, 11: 26, 20: 29, 17: 4, 19: 7, 27: 1, 21: 9}
print(board_moves(30, J), board_moves(12, {2: 11, 8: 1}))
What is printed?
  1. A. 3 1
  2. B. 3 2
  3. C. 4 2
  4. D. 5 2

Correct answer: B. 3 2

Each square is a node with up to 6 edges (after applying jumps); BFS gives the fewest rolls. 30 squares: 1 → (roll 2) 3 ↗ 22 → (roll 4) 26 → (roll 4) 30 = 3 rolls; two rolls cannot work because after one roll the farthest square is 22. 12 squares: 1 → 2 ↗ 11 → 12 = 2. Greedy 'always roll the biggest useful number' can land on snakes (e.g. 27 → 1). O(6n).

More Coding Interview Problems questions

Exams that ask this topic