Data Structures & AlgorithmsHardProduct Company SDE · Amazon/Microsoft-style OA

Problem: Courses with prerequisites [a, b] (b before a). Return one valid order using Kahn's algorithm with a min-heap for ties, or [] if impossible.

Problem: Courses with prerequisites [a, b] (b before a). Return one valid order using Kahn's algorithm with a min-heap for ties, or [] if impossible.
import heapq
def order(n, pre):
    adj = [[] for _ in range(n)]; indeg = [0] * n
    for a, b in pre:
        adj[b].append(a); indeg[a] += 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 adj[u]:
            indeg[v] -= 1
            if indeg[v] == 0: heapq.heappush(h, v)
    return out if len(out) == n else []
print(order(6, [[2, 5], [0, 5], [0, 4], [1, 4], [3, 2], [1, 3]]), order(3, [[0, 1], [1, 2], [2, 0]]))
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, 3, 1] [0, 1, 2]

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

Start with indegree-0 nodes {4, 5}; the heap always takes the smallest available. 4 frees nothing on its own (0 and 1 still wait), 5 frees 0 and 2, then 0, 2, 3 (freed by 2) and 1 (freed by 3). In the cycle 0→1→2→0 no node has indegree 0, so fewer than n nodes come out → []. O((V + E) log V) with the heap, O(V + E) with a plain queue.

More Coding Interview Problems questions

Exams that ask this topic