Kahn's Algorithm - Topological Sorting
A topological sort lays every vertex of a directed acyclic graph (DAG) out in
a line such that every edge points forward - for every edge u → v, u
appears before v. Kahn's algorithm builds that line by repeatedly placing
whichever vertices have no remaining prerequisites (in-degree 0).
Why the order is a lineup and not a walk, why the cycle test is
len(order) == n rather than "the pool started empty," and what the pool's
container choice does and does not affect are all on
Cycles & Ordering. Step through it
here:
FIG. TOPOLOGICAL SORTING● INTERACTIVE
visualization loads as you reach it
Problems
207. Course Schedule
Medium·
1
Kahn's Algorithm
O(2(V + E))
O(V + E)
FIG. COURSE SCHEDULE● INTERACTIVE
visualization loads as you reach it
- Time
- O(2(V + E))
- Building
adjandin_degreecostsO(V + E), whereV = numCoursesandE = len(prerequisites). - The BFS then dequeues each of the
Vnodes once and scans each of theEedges once more - a second, distinctO(V + E)pass,2(V + E). - Space
- O(V + E)
adjstoresVkeys andEtotal edge entries,in_degreeholdsVentries, andqueueholds up toVnodes.
802. Find Eventual Safe States
Medium·
1
Kahn's Algorithm
O(2(V + E) + V log V)
O(sort + V + E)
FIG. FIND EVENTUAL SAFE STATES● INTERACTIVE
visualization loads as you reach it
- Time
- O(2(V + E) + V log V)
Vislen(graph)(number of nodes),Eis the total number of edges acrossgraph.- Building the reversed
adjlist andin_degreemap walks every node and every edge once -O(V + E). - The
while queueloop (Kahn's algorithm) visits every node and every reversed edge once more - anotherO(V + E)- together2(V + E). sorted(list(safe_nodes))sorts up toVnodes at the end -O(V log V).- Space
- O(sort + V + E)
adjstores every reversed edge,O(E).in_degree,queue, andsafe_nodeseach hold at mostVnodes.- Sorting algorithms are typically
O(log n)space (in-place, recursion stack only), but Python'slist.sort()is Timsort, which allocates up toO(n)auxiliary space in the worst case - that's whatsortstands for here.
1136. Parallel Courses
Medium·
1136Parallel Courses
1
Kahn's Algorithm
O(3n + 2e)
O(3n + e)
FIG. PARALLEL COURSES● INTERACTIVE
visualization loads as you reach it
- Time
- O(3n + 2e)
nis the number of courses,eislen(relations).- Building
adj/in_degree/nodesfromrelationsis oneO(e)pass. - Filling in isolated courses (
for i in range(1, n + 1)) is oneO(n)pass. - Building the initial
queuefromnodesis anotherO(n)pass. - The BFS pops each course at most once (
O(n)) and relaxes each edge inadj[u]at most once across the whole run (O(e)). - Node-sized passes:
n(fill isolated) +n(build queue) +n(BFS pops) =3n. Edge-sized passes:e(build) +e(relax) =2e. - Space
- O(3n + e)
adjstores each of theeedges once across its lists -O(e).in_degree,nodes, andqueueeach hold up toncourses - three separateO(n)allocations,3n.
2115. Find All Possible Recipes from Given Supplies
Medium·
1
Kahn'a Algorithm
O(R + m + S)
O(R + m + S)
FIG. FIND ALL POSSIBLE RECIPES FROM GIVEN SUP● INTERACTIVE
visualization loads as you reach it
- Time
- O(R + m + S)
Ris the number of recipes,mis the total number of ingredient entries across allingredientslists, andSis the number of supplies.- Building
available_suppliesfromsuppliesisO(S). - The nested loop over
recipes/ingredientsbuildsadjandin_degreeinO(m). - Kahn's BFS pops each of the
Rrecipes once and walks each of themadjacency edges once -O(R + m). - Space
- O(R + m + S)
adjholds up tomentries,in_degreeholdsRentries, andavailable_suppliesholdsSentries.queueandcreated_recipeseach hold up toRrecipes.