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?- A. [5, 4, 2, 3, 1, 0] []
- B. [4, 5, 2, 0, 3, 1] []
- C. [4, 5, 0, 2, 3, 1] []
- 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
- Problem: Detect a cycle in a directed dependency graph with three-colour DFS. python def hascycle(n, edges): adj = [[] for in range(n)]…
- Problem: Find the shortest travel time from node 0 to every node in a road network with non-negative weights. python import heapq def…
- Problem: A network has V = 10⁵ routers and E = 2 × 10⁵ links with latencies that can be negative (but no negative cycle). Which…
- Problem: Union-find with path compression answers which friends are in the same circle. How many circles remain after the unions? python…
- Problem: Find the minimum total cost to connect all offices (minimum spanning tree) using Kruskal's algorithm. python def kruskal(n…
- Problem: Find the length of the shortest transformation from a start word to an end word, changing one letter at a time, every…