Data Structures & AlgorithmsHardAmazon · Microsoft OA
Problem: Topological order produced by DFS (append a node after all its descendants, then reverse).
Problem: Topological order produced by DFS (append a node after all its descendants, then reverse).
g = {0: [2, 1], 1: [3], 2: [3, 4], 3: [5], 4: [5], 5: []}
seen, order = set(), []
def dfs(u):
seen.add(u)
for v in g[u]:
if v not in seen: dfs(v)
order.append(u)
for u in g:
if u not in seen: dfs(u)
print(order[::-1])What is printed?- A. [0, 1, 2, 4, 3, 5]
- B. [0, 1, 2, 3, 4, 5]
- C. [0, 2, 4, 3, 1, 5]
- D. [5, 3, 4, 2, 1, 0]
Correct answer: A. [0, 1, 2, 4, 3, 5]
DFS from 0 visits 2 first: 2 → 3 → 5 (finish 5, 3), then 4 (finish 4), finish 2; then 1 (3 already seen, finish 1), finish 0. Finish order 5, 3, 4, 2, 1, 0 reversed gives [0, 1, 2, 4, 3, 5] — a valid order different from BFS/Kahn's.
More Coding Interview Problems questions
- Problem: Maximum bipartite matching between workers (left) and jobs (right) with Kuhn's augmenting-path algorithm. python adj = {0: [0…
- Problem: Maximum flow from s = 0 to t = 5 with Edmonds–Karp (BFS augmenting paths). python from collections import deque cap = [[0]6 for…
- Problem: Does an undirected connected graph have an Euler path / Euler circuit? (count odd-degree vertices) python from collections import…
- Problem: Count Hamiltonian paths (ordered sequences visiting every vertex once) in a small undirected graph with bitmask DP. python n = 5…
- Problem: Reconstruct an actual longest strictly increasing subsequence with the O(n²) DP and parent pointers (the first maximal end index…
- Problem: Minimum number of single-character insertions plus deletions to turn a into b (no replacements). python def insdel(a, b): m, n =…