Data Structures & AlgorithmsHardProduct Company SDE · graph round

Problem: Topological order by DFS finishing times (reverse postorder) for the DAG adj = {0: [1, 2], 1: [3], 2: [3], 3: []} on 4 vertices. What is printed?

Problem: Topological order by DFS finishing times (reverse postorder) for the DAG adj = {0: [1, 2], 1: [3], 2: [3], 3: []} on 4 vertices. What is printed?
def topo(n, adj):
    seen = [False] * n
    out = []
    def dfs(u):
        seen[u] = True
        for v in adj[u]:
            if not seen[v]:
                dfs(v)
        out.append(u)
    for i in range(n):
        if not seen[i]:
            dfs(i)
    return out[::-1]
adj = {0: [1, 2], 1: [3], 2: [3], 3: []}
print(topo(4, adj))
What is printed?
  1. A. [0, 1, 2, 3]
  2. B. [0, 2, 1, 3]
  3. C. [0, 1, 3, 2]
  4. D. [3, 2, 1, 0]

Correct answer: B. [0, 2, 1, 3]

Vertex 3 finishes first, then 1, then 2 and finally 0, so reversing gives 0, 2, 1, 3. The order 0 1 2 3 is a topological order too, but the DFS produces a different one.

More Coding Interview Problems questions

Exams that ask this topic