Skip to main content
←Architecture WorkspaceArchOSWorkspaces/
Sign in
ALGORITHM CANVAS · DAG IN-DEGREE QUEUE · TIME O(V + E) · SPACE O(V)
Kahn Topological Sort & Cycle Detection
Peel off nodes with in-degree 0 one by one; if fewer than V nodes are peeled, the remaining graph contains a dependency cycle.
GRAPH FRONTIER · VISITED: 1/4DBindeg=0APIindeg=1Cacheindeg=0Edgeindeg=1
STEP 1/4 · L10
u="Cache"order=["Cache"]indeg={"DB":0,"Cache":0,"API":1,"Edge":1}
PYTHON 3.12 · INSTANT PREVIEW
1from collections import deque
2
3def kahn_topo():
4 adj = {"DB": ["API"], "Cache": ["API"], "API": ["Edge"], "Edge": []}
5 indeg = {"DB": 0, "Cache": 0, "API": 2, "Edge": 1}
6 q = deque(["Cache", "DB"])
7 order = []
8 while q:
9 u = q.popleft()
10 order.append(u)
11 for v in adj[u]:
12 indeg[v] -= 1
13 if indeg[v] == 0:
14 q.append(v)
15 return order