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·
Kahn's Algorithm
O(3V + 2E)O(V + E)
FIG. COURSE SCHEDULE● INTERACTIVE
visualization loads as you reach it
802. Find Eventual Safe States
Medium·
Kahn's Algorithm
O(3V + 2E + V log V)O(sort + V + E)
FIG. FIND EVENTUAL SAFE STATES● INTERACTIVE
visualization loads as you reach it
1136. Parallel Courses
Medium·
1136Parallel Courses
Kahn's Algorithm
O(3n + 2e)O(3n + e)
FIG. PARALLEL COURSES● INTERACTIVE
visualization loads as you reach it
2115. Find All Possible Recipes from Given Supplies
Medium·
Kahn'a Algorithm
O(3R + 2m + S)O(R + m + S)
FIG. FIND ALL POSSIBLE RECIPES FROM GIVEN SUP● INTERACTIVE
visualization loads as you reach it