Intermediate Topic 33 of 51 Algorithms
Topological Sort
Linear ordering of a DAG respecting dependencies.
How it works
A topological sort orders the vertices of a directed acyclic graph so that every edge goes from an earlier to a later vertex. It can be computed with DFS by adding vertices to the front of a list as they finish, or with Kahn's algorithm by repeatedly removing vertices with no incoming edges. Both run in O(V + E), and a leftover cycle shows that no ordering exists.
Where it is used
Build systems, course prerequisites, task scheduling, spreadsheet cell recalculation, package dependency installation and compiler instruction ordering use topological sorting.
Common pitfall
It only exists for acyclic graphs, so always detect cycles and report them clearly. Many valid orders typically exist, so do not rely on a particular one unless tie-breaking is specified. Edge direction confusion reverses the result. Forgetting vertices with no edges leaves them out.
Where it fits in the course
Topological Sort is topic 33 of 51 in Algorithms, rated Intermediate. It follows Depth-First Search. The next topic is Dijkstra's Algorithm.
Practice and explore
- Open the interactive lesson, with a mini quiz.
- Take the Algorithms quiz.
- Explore the Sorting Algorithms visualizer: Bubble, selection, insertion, merge and quick sort animated.
How to study this topic
- Read the explanation above and restate the definition in your own words.
- Open the interactive lesson and answer its mini quiz.
- Read the common pitfall, then write a short example that avoids it.
- Check your understanding in the Algorithms quiz, and revisit the topic if you miss a question.
Frequently asked questions
What is Topological Sort?
Where do people use Topological Sort?
What is the most common mistake with Topological Sort?
What should I learn before this topic?
How can I practice it?
Is Topological Sort hard to learn?
How long does it take to learn Topological Sort?
Which topics are related to Topological Sort?
What should I study after Topological Sort?
Related topics
- Depth-First Search (Algorithms)
- Dijkstra's Algorithm (Algorithms)
- Breadth-First Search (Algorithms)
- Bellman-Ford Algorithm (Algorithms)