Data Structures & AlgorithmsVery hardCodeforces Div2 C/D · Amazon SDE OA

A task graph has six nodes 0 to 5 and dependencies 5→0, 4→0, 4→1, 5→2, 2→3, 3→1 (an edge u→v means u must finish before v). Among all valid orders, the lexicographically smallest one is wanted. Run the min-heap Kahn algorithm and print the order.

A task graph has six nodes 0 to 5 and dependencies 5→0, 4→0, 4→1, 5→2, 2→3, 3→1 (an edge u→v means u must finish before v). Among all valid orders, the lexicographically smallest one is wanted. Run the min-heap Kahn algorithm and print the order.
import heapq
n=6; E=[(5,0),(4,0),(4,1),(5,2),(2,3),(3,1)]
g=[[] for _ in range(n)]; indeg=[0]*n
for u,v in E: g[u].append(v); indeg[v]+=1
h=[i for i in range(n) if indeg[i]==0]; heapq.heapify(h); out=[]
while h:
    u=heapq.heappop(h); out.append(u)
    for v in g[u]:
        indeg[v]-=1
        if indeg[v]==0: heapq.heappush(h,v)
print(out)
What is printed?
  1. A. [4, 5, 0, 2, 3, 1]
  2. B. [5, 4, 2, 0, 3, 1]
  3. C. [5, 4, 2, 3, 1, 0]
  4. D. [5, 2, 3, 4, 0, 1]

Correct answer: A. [4, 5, 0, 2, 3, 1]

A min-heap of ready nodes pops the smallest available label, which gives the lexicographically smallest order. Reverse postorder is a valid topological order but not the smallest, and a LIFO ready list or a reverse-sorted queue pops the wrong node first.

More Coding Interview Problems questions

Exams that ask this topic