Skip to contentKEEP THE CRAFTTHE SANCTUARY

Kahn's Algorithm

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 Code Labs

Count Every Incoming Edge

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.

Seed All Zero Indegree Nodes

Every node with zero unresolved prerequisites is ready. Seeding all of them is required to cover disconnected DAG components and isolated vertices.

Trace Kahn Indegree Updates

Reference
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 trace
Practice

Implement kahn_trace(node_count,edges). Return [removed,indegree,ready] after each queue removal using ascending ready order.

Public tests

  • Remove outgoing edges once

Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor

Trace Kahn Indegree Updates

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 trace

Wait for Both Prerequisites to Disappear

Predict 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.
Print 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.

Remove Edges as Nodes Leave

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.

Order Nodes with Kahn Algorithm

Reference
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 []
Practice

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.

Public tests

  • Detect unprocessed cyclic nodes

Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor

Order Nodes with Kahn Algorithm

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 []

Use Processed Count to Detect Cycles

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.

Explain It in an Interview

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 Version Note

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)

Complexity & Invariants

Interview bounds depend on the stated representation, input model, and real Python operations.

OperationAverageWorstInterview note
FIFO Kahn orderO(V + E)O(V + E)The second Lab uses deque and ascending initial seeding, then discovery-order appends.
Heap-ready traceO(E + V^2 log(V+1)) upper boundO(E + V^2 log(V+1)) upper boundThe 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.

Space

O(V + E) graph plus counts/frontier; trace snapshots can store O(V^2) cells.

Assumptions

  • The trace and FIFO Labs deliberately use different ready policies.
  • Repeated full indegree snapshots are teaching output, not part of the linear untraced algorithm.

Invariants Worth Saying Aloud

  1. Indegree counts edges from unprocessed sources.
  2. A node becomes eligible exactly when that count reaches zero.
  3. Each outgoing edge is removed once when its source is processed.

When To Use Or Avoid Kahn's Algorithm

Use It When

  • Use indegrees when readiness is naturally an incoming-dependency count.
  • Use a FIFO queue for any deterministic valid order, or a min heap for the smallest ready node.

Choose Another Tool When

  • Kahn reports a blocked remainder but does not itself reconstruct the cycle.
  • Do not interpret zero outgoing edges as readiness; a sink may still have prerequisites.

Common Pitfalls

These are the mistakes most likely to survive a happy-path example and fail a boundary case.

Seeding only one available component

Choosing only node 0 leaves isolated ready nodes unprocessed even though no dependency blocks them.

Prevent it: Initialize with all zero-indegree nodes.

Avoid

ready = [0] if indegree[0] == 0 else []

Use instead

ready = [node for node, degree in enumerate(indegree) if degree == 0]

Releasing a node after only one predecessor

With indegree 2, one removed predecessor leaves count 1. Enqueueing now violates the remaining edge.

Prevent it: Release only after decrementing to exactly zero.

Avoid

indegree[neighbor] -= 1
released = True

Use instead

indegree[neighbor] -= 1
released = indegree[neighbor] == 0

Decrementing a duplicate edge only once

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.

Avoid

indegree[target] -= len(set(targets))

Use instead

indegree[target] -= len(targets)

Reviewed References

Official Python documentation supports language behavior. Canonical problem pages provide additional practice context.