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?- A. [4, 5, 0, 2, 3, 1]
- B. [5, 4, 2, 0, 3, 1]
- C. [5, 4, 2, 3, 1, 0]
- 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
- Eight vertices 0..7 receive the edges (0,1), (2,3), (4,5), (1,2), (5,6) in that order in a disjoint-set structure with union by size and…
- Compute the sum over all subarrays of the minimum element, for a = [3, 1, 2, 1, 3]. Subarrays are counted by position, so equal values in…
- Find the sum of the maximum of every window of length 3 in a = [1, 3, −1, −3, 5, 3, 6, 7] (windows slide one step at a time). python…
- In the reflected binary Gray code, the number with index i is i XOR (i >> 1). Using 0-based indices, what is the value printed for i = 5…
- How many binary strings of length 30 contain neither the substring "11" nor the substring "000"? python n=30 dp={('0',1):1,('1',1):1} for…
- How many primes p satisfy p ≤ 1,000,000 and p ≡ 3 (mod 4)? python N=106 s=bytearray([1])(N+1); s[0]=0; s[1]=0 for i in…