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?- A. 2
- B. 3
- C. 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
- Problem: A grid has exactly two islands (1s). Find the minimum number of 0s to flip to connect them (BFS outward from the first island)…
- Problem: Return the city that can reach the FEWEST other cities within a distance threshold (largest index on ties), using Floyd–Warshall…
- Problem: Count all paths from node 0 to node n − 1 in a DAG (memoised DFS). python from functools import lrucache g = {0: [1, 2, 3], 1…
- Problem: Rebuild a binary tree from its inorder and postorder traversals (distinct values) and print its preorder. python def prefrom(ino…
- Problem: Lowest common ancestor in a general binary tree (not a BST), with the recursive 'return whichever side found something' method…
- Problem: Delete the nodes with given values from a binary tree and return the roots of the remaining forest, sorted. python class T: def…