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?- A. 3 1
- B. 3 2
- C. 4 2
- 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
- Problem: Find the bug: Kahn's algorithm is used to schedule build steps, but nobody checks whether a cycle exists. What does it return for…
- Problem: n, q ≤ 2·10⁵ operations of two kinds: add v to every a[l..r], and ask for sum a[l..r]. A Fenwick tree with two arrays supports…
- Problem: For n = 2·10⁵, compute Σ over all subarrays of (max − min). Sum of maxima minus sum of minima, each via monotonic stacks with…
- Problem: Adjacent piles in a row are merged two at a time; merging costs the combined size. Minimise the total cost (interval DP over [i…
- Problem: Rain on a height grid flows to a neighbour with height ≤ the current cell. The west/north edge touches one sea, the east/south…
- Problem: A recursive routine splits a problem of size n into parts n/3 and 2n/3 and does n extra work: W(n) = W(n/3) + W(2n/3) + n. The…