Topological Sort
Software Engineer path · lesson 27 of 99Order tasks with dependencies! Visualize Kahn's Algorithm using In-Degrees. Crucial for build systems, course scheduling, and resolving dependencies.
Directed, like A>B meaning A must come before B. Badges show remaining in-degree.
Count each node’s incoming edges.
- 1indeg[v] = number of edges into v
- 2queue = every v with indeg[v] == 0
- 3while queue:
- 4 u = queue.popleft(); order.append(u)
- 5 for v in out(u): indeg[v] -= 1; if indeg[v] == 0: queue.append(v)
- 6if len(order) < n: the graph has a cycle
- Nodes output
- 0 / 6
- Edges removed
- 0 / 6
Tap any element in the diagram to inspect its state at this step.
Keys: ← → step, Space play/pause. Predict mode pauses before key steps and asks what happens next.
Kahn’s algorithm
Order the steps of a topological sort by in-degree.
Tap a piece, then tap where it goes — or drag it. Tap the tray to take one back.
- 1Drop a step here
- 2Drop a step here
- 3Drop a step here
- 4Drop a step here
- 5Drop a step here
Test your knowledge
Topological Sort is only possible for which type of graph?
Write the code
Course Schedule II
function findOrder(numCourses, prerequisites) {
// Your code here
}The short version
Think of getting dressed. You must put on socks before shoes, and underwear before pants. You can't just put things on in random order; dependencies must be respected.
In more depth
Order of Operations
Topological Sorting is a linear ordering of vertices such that for every directed edge u -> v, vertex u comes before v in the ordering.
Prerequisite: The graph must be a Directed Acyclic Graph (DAG). If there is a cycle (A -> B -> A), no linear ordering is possible.
Kahn's Algorithm (BFS):
When to reach for this
- Scheduling tasks with dependencies
- Build systems (compiling dependencies first)
- Detecting cycles in a directed graph
Interview Questions
References & Further Reading
Love this visualization?
Sign up to track your progress, earn achievements, use the AI assistant, and access your personal learning dashboard.
100% free • No credit card required