Data Structures & AlgorithmsHardGoogle · Flipkart interview

Problem: Task IDs 0..5 with dependencies u → v (u before v). The scheduler always runs the SMALLEST available ID next.

Problem: Task IDs 0..5 with dependencies u → v (u before v). The scheduler always runs the SMALLEST available ID next.
import heapq
def order(n, edges):
    g = [[] for _ in range(n)]; indeg = [0] * n
    for u, v in edges:
        g[u].append(v); indeg[v] += 1
    h = [i for i in range(n) if indeg[i] == 0]; heapq.heapify(h)
    res = []
    while h:
        u = heapq.heappop(h); res.append(u)
        for v in g[u]:
            indeg[v] -= 1
            if indeg[v] == 0: heapq.heappush(h, v)
    return res
print(*order(6, [(5,2),(5,0),(4,0),(4,1),(2,3),(3,1)]))
What is printed?
  1. A. 5 4 2 3 1 0
  2. B. 4 5 2 0 3 1
  3. C. 4 5 0 2 3 1
  4. D. 4 5 0 2 1 3

Correct answer: C. 4 5 0 2 3 1

Sources are 4 and 5; 4 runs first and frees nothing, then 5 frees 0 and 2. The heap picks 0 before 2, then 2 frees 3, and 3 frees 1, giving 4 5 0 2 3 1. '5 4 2 3 1 0' is a DFS-based topological order, valid but not the smallest-first one.

More Coding Interview Problems questions

Exams that ask this topic