Data Structures & AlgorithmsHardAmazon · Microsoft OA

Problem: Roads are one-way (a → b). Reorient the fewest roads so every city can reach city 0 (the roads form a tree).

Problem: Roads are one-way (a → b). Reorient the fewest roads so every city can reach city 0 (the roads form a tree).
def reorder(n, roads):
    g = [[] for _ in range(n)]
    for a, b in roads: g[a].append((b, 1)); g[b].append((a, 0))
    seen, st, flips = {0}, [0], 0
    while st:
        u = st.pop()
        for v, away in g[u]:
            if v not in seen: seen.add(v); flips += away; st.append(v)
    return flips
print(reorder(7, [(0, 1), (2, 1), (3, 2), (0, 4), (5, 4), (4, 6)]))
What is printed?
  1. A. 2
  2. B. 3
  3. C. 4
  4. D. 6

Correct answer: B. 3

Walking outward from 0, every road that points AWAY from 0 must be flipped: 0→1, 0→4 and 4→6. The roads 2→1, 3→2 and 5→4 already point toward 0. Answer 3.

More Coding Interview Problems questions

Exams that ask this topic