Topological Sort
Arranges the vertices of a directed acyclic graph (DAG) in a line so that every edge points only forward. Kahn's algorithm keeps nodes with indegree 0 in a queue and emits them in turn, forming the basis of task scheduling, dependency resolution, and build ordering.
01Topological Sort
Explore How It WorksStarting topological sort. Count each node's indegree, then enqueue A·B, which have indegree 0.
Pop A from the queue and append it to the order. Remove edge A→C, lowering C's indegree from 2 to 1.
Pop B and append it to the order. B→C drops C's indegree to 0, so enqueue C.
Pop C. C→D and C→E drop D's and E's indegree to 0, so both enter the queue.
Pop D. D→F lowers F's indegree from 2 to 1, but it isn't 0 yet, so don't enqueue it.
Pop E. E→F drops F's indegree to 0, so enqueue F last.
Pop F and append it to the order. The queue is empty, so every node is now listed in topological order.
Done · topological order A → B → C → D → E → F. A valid ordering where every edge points only forward.
02 Understand It Simply
For EveryoneOrders tasks with dependencies so that every prerequisite comes first. If the graph has a cycle, no such order exists.
Lines up the vertices of a directed graph so that 'what must come first' comes first.
It pulls out nodes with indegree 0 one at a time.
- –Task scheduling
- –build dependencies
- –course prerequisites
03 Python Implementation
A clean, readable reference implementation of the core logic of Topological Sort.
04 Frequently Asked Questions
FAQWhat is Topological Sort?+
Arranges the vertices of a directed acyclic graph (DAG) in a line so that every edge points only forward. Kahn's algorithm keeps nodes with indegree 0 in a queue and emits them in turn, forming the basis of task scheduling, dependency resolution, and build ordering.
What is the time complexity of Topological Sort?+
The time complexity of Topological Sort is O(V+E). Follow the step-by-step visualization to see exactly why.
Where is Topological Sort used?+
Task scheduling, build dependencies, course prerequisites.
What's a simple analogy for Topological Sort?+
Orders tasks with dependencies so that every prerequisite comes first. If the graph has a cycle, no such order exists.
