Home
DSA Visualizer
Data Structures
Topological Sort
Topological Sort
A topological sort is a linear ordering of the vertices of a directed acyclic graph (DAG) in which, for every directed edge u -> v, vertex u comes before v.
IN-DEGREES
Queue (in-degree 0)
Sorted order
Nothing emitted yet
Count each node's prerequisites. A has none, so it can go first.
Next
A has no unmet prerequisite. Emit it — position 1.
Algorithm
Intuition
Imagine you are getting dressed. You must put on socks before shoes, and underwear before pants.
You can't put on shoes first, then socks. Some tasks have dependencies.
Topological Sort gives you a valid order to perform tasks so that all dependencies are met.
Concept
Topological sorting puts the vertices of a directed graph in an order where every edge points forward: for an edge u -> v, u appears somewhere before v. Picture a valid order in which to take courses when some are prerequisites of others. Most graphs have more than one valid order.
It is only possible if the graph has no cycles (DAG).
How it Works
- Calculate in-degree (number of incoming edges) for each node.
- Add nodes with 0 in-degree to a Queue.
- Process Queue: remove node
u, add to result. - Decrease in-degree of neighbors. If a neighbor becomes 0, add to Queue.
- Repeat until Queue is empty.
Step-by-Step Breakdown
Watch the visualization:
- Solid blue node: The node the current step acts on.
- Pale blue node with a blue outline: Waiting: in Kahn's queue, or on the DFS stack.
- Green node: Added to the sorted order.
- Red node: On a cycle, so no topological order exists.
- In-Degrees: In Kahn's mode, the number above a node is its count of unmet prerequisites.
When to Use
Use Topological Sort when:
- Scheduling tasks with dependencies (e.g., project management, build systems).
- Resolving symbol dependencies in linkers.
- Course prerequisite planning.
- Finding a cycle in a graph (if sort fails).
When NOT to Use
- Cyclic Graphs: It's impossible to topologically sort a graph with a cycle.
- Undirected Graphs: Only applies to directed graphs.
How to Identify
Problems about "ordering tasks", "prerequisites", "dependencies", or "build order" typically require Topological Sort.
Preparing for interviews? This topic is also taught as a pattern:
Ordering Dependencies (Topological Sort)
Applying for software engineering roles? Free, no sign-up:
