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?- A. [0, 1, 2, 3]
- B. [0, 2, 1, 3]
- C. [0, 1, 3, 2]
- 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
- Problem: Find the length of the longest common substring (contiguous) of 'abcdef' and 'zcdemn'. python def lcssub(a, b): best = 0 dp =…
- Problem: How many (possibly overlapping) occurrences of the pattern 'ana' are in 'banana'? python s = 'banana' p = 'ana' print(sum(1 for i…
- Problem: Each element of [2, 3, 1, 1, 4] is the maximum jump length from that index. What is the minimum number of jumps to reach the last…
- Problem: A circular route has gas = [1, 2, 3, 4, 5] and cost = [3, 4, 5, 1, 2] (cost to travel from station i to i+1). Find the start…
- Problem: What is the minimum number of intervals to remove so that the rest are pairwise non-overlapping (touching at an endpoint is…
- Problem: The prefix sums of [2, 5, 1, 7, 3] are stored in a list p. What is printed by the code, which finds the first index whose prefix…