← Graph Exploration

Micro-Drill #146 — Topological sort (Kahn's)

Graph Exploration Target: 15s

BFS-based topo sort processes zero-indegree nodes first. Detects cycles if order is incomplete.

from collections import deque
q = deque(n for n in range(V) if indeg[n] == 0)
order = []
while q:
    u = q.popleft()
    order.append(u)
    for v in adj[u]:
        indeg[v] -= 1
        if indeg[v] == 0: q.append(v)

Type it from memory. Go.

Practice Problems

Related Coding Drills

← Micro #145 Micro #147 →