Python 3.11+
The code uses standard Python syntax and containers supported by the browser Judge. The Kahn's Algorithm proof does not depend on a minor Python release.
Verify in Python docs(opens in a new tab)Maintain unresolved incoming-edge counts and release a vertex exactly when its last prerequisite disappears. Compare a linear FIFO frontier with smallest-ready heap ordering and use processed count to detect blocked cycles.
1 practice exercise4 interview problems
Recognize it when Prerequisites become satisfied as earlier nodes are removed.
Checking your account…
Kahn’s algorithm starts by computing indegree for every node from every directed edge. Indegree represents unresolved prerequisites, including duplicate edges if the input permits them.
Every node with zero unresolved prerequisites is ready. Seeding all of them is required to cover disconnected DAG components and isolated vertices.
import heapq
def kahn_trace(node_count,edges):
adjacency=[[] for _ in range(node_count)];indegree=[0]*node_count
for source,target in edges:adjacency[source].append(target);indegree[target]+=1
ready=[n for n in range(node_count) if indegree[n]==0];heapq.heapify(ready);trace=[]
while ready:
node=heapq.heappop(ready)
for neighbor in adjacency[node]:
indegree[neighbor]-=1
if indegree[neighbor]==0:heapq.heappush(ready,neighbor)
trace.append([node,indegree.copy(),sorted(ready)])
return traceImplement kahn_trace(node_count,edges). Return [removed,indegree,ready] after each queue removal using ascending ready order.
Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor
import heapq
def kahn_trace(node_count,edges):
adjacency=[[] for _ in range(node_count)];indegree=[0]*node_count
for source,target in edges:adjacency[source].append(target);indegree[target]+=1
ready=[n for n in range(node_count) if indegree[n]==0];heapq.heapify(ready);trace=[]
while ready:
node=heapq.heappop(ready)
for neighbor in adjacency[node]:
indegree[neighbor]-=1
if indegree[neighbor]==0:heapq.heappush(ready,neighbor)
trace.append([node,indegree.copy(),sorted(ready)])
return tracePredict the existing heap trace for a join followed by a final dependent. The first removal must not release the join node. Each row copies the complete indegree array after outgoing edges are removed.
| Step | Executed statement | State | Why |
|---|---|---|---|
| Build | indegree[target]+=1 |
indegree=[0, 0, 2, 1] |
Node 2 requires both 0 and 1; node 3 requires 2. |
| Remove 0 | node=heapq.heappop(ready); indegree[neighbor]-=1 |
after iteration: indegree=[0, 0, 1, 1], ready=[1] |
Node 2 is still blocked by node 1. |
| Remove 1 | node=heapq.heappop(ready); indegree[neighbor]-=1; heapq.heappush(ready,neighbor) |
after iteration: ready=[2] |
The second removed edge releases node 2 exactly once. The push executes only in the actual zero-indegree branch. |
| Remove 2 | node=heapq.heappop(ready); indegree[neighbor]-=1; heapq.heappush(ready,neighbor) |
after iteration: ready=[3] |
Node 3 can now become eligible. The push executes only in the actual zero-indegree branch. |
| Record final removal | node=heapq.heappop(ready); trace.append([node,indegree.copy(),sorted(ready)]) |
removed=3, all counts zero, ready=[] |
Snapshots expose the state after each removal rather than its initial counts. |
| Output | |
|---|---|
print(kahn_trace(4, [[0, 2], [1, 2], [2, 3]])) |
[[0, [0, 0, 1, 1], [1]], [1, [0, 0, 0, 1], [2]], [2, [0, 0, 0, 0], [3]], [3, [0, 0, 0, 0], []]] |
The FIFO order Lab seeds available nodes in ascending index order but appends later discoveries behind waiting nodes. It does not promise the heap trace’s globally smallest-ready policy.
When a ready node is processed, decrement each outgoing neighbor once. Enqueue a neighbor exactly when its indegree becomes zero, never before and never repeatedly.
from collections import deque
def kahn_order(node_count,edges):
adjacency=[[] for _ in range(node_count)];indegree=[0]*node_count
for source,target in edges:adjacency[source].append(target);indegree[target]+=1
queue=deque(node for node in range(node_count) if indegree[node]==0);order=[]
while queue:
node=queue.popleft();order.append(node)
for neighbor in adjacency[node]:
indegree[neighbor]-=1
if indegree[neighbor]==0:queue.append(neighbor)
return order if len(order)==node_count else []Implement kahn_order(node_count,edges). Return FIFO ready order, seeding initial zero-indegree nodes in ascending index order and appending later discoveries in input-edge order; return [] if a cycle prevents processing all nodes.
Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor
from collections import deque
def kahn_order(node_count,edges):
adjacency=[[] for _ in range(node_count)];indegree=[0]*node_count
for source,target in edges:adjacency[source].append(target);indegree[target]+=1
queue=deque(node for node in range(node_count) if indegree[node]==0);order=[]
while queue:
node=queue.popleft();order.append(node)
for neighbor in adjacency[node]:
indegree[neighbor]-=1
if indegree[neighbor]==0:queue.append(neighbor)
return order if len(order)==node_count else []If the queue empties before V nodes are processed, the remaining subgraph has no zero-indegree node and therefore contains a directed cycle. The algorithm takes O(V + E) time and space.
Say: “Indegree counts unresolved prerequisites. Zero-indegree nodes are safe next choices; removing one resolves each outgoing prerequisite. If processed count is short, a cycle blocked the rest.” State how ready-node ordering affects deterministic output.
Python 3.11+
The code uses standard Python syntax and containers supported by the browser Judge. The Kahn's Algorithm proof does not depend on a minor Python release.
Verify in Python docs(opens in a new tab)Interview bounds depend on the stated representation, input model, and real Python operations.
| Operation | Average | Worst | Interview note |
|---|---|---|---|
| FIFO Kahn order | O(V + E) | O(V + E) | The second Lab uses deque and ascending initial seeding, then discovery-order appends. |
| Heap-ready trace | O(E + V^2 log(V+1)) upper bound | O(E + V^2 log(V+1)) upper bound | The heap core uses O(E + V log(V+1)); every removal also copies V indegrees and sorts up to V ready entries for a diagnostic snapshot. |
O(V + E) graph plus counts/frontier; trace snapshots can store O(V^2) cells.
These are the mistakes most likely to survive a happy-path example and fail a boundary case.
Choosing only node 0 leaves isolated ready nodes unprocessed even though no dependency blocks them.
Prevent it: Initialize with all zero-indegree nodes.
ready = [0] if indegree[0] == 0 else []ready = [node for node, degree in enumerate(indegree) if degree == 0]Where you will hit this: Topological Sort in Layers(opens in a new tab)
With indegree 2, one removed predecessor leaves count 1. Enqueueing now violates the remaining edge.
Prevent it: Release only after decrementing to exactly zero.
indegree[neighbor] -= 1
released = Trueindegree[neighbor] -= 1
released = indegree[neighbor] == 0Where you will hit this: Topological Sort in Layers(opens in a new tab)
If two parallel incoming edges were counted, removing only one leaves a false blocked count.
Prevent it: Preserve edge multiplicity consistently in adjacency and indegree updates.
indegree[target] -= len(set(targets))indegree[target] -= len(targets)Where you will hit this: Course Schedule(opens in a new tab)
Official Python documentation supports language behavior. Canonical problem pages provide additional practice context.
python-docs · checked 2026-07-12
python-docs · checked 2026-07-27