A topic in the Open Knowledge Graph — a free, open map of 15,290 topics and the order to learn them in.

Topological Sort

College Depth 87 in the knowledge graph ☐ I know this ☆ Set as goal
151topics build on this
443prerequisites beneath it
See this on the map →
Depth-First Search (DFS)Depth-First Search: Implementation and Applications+3 more→→Dynamic ProgrammingStrongly Connected Components: Kosaraju and Tarjan Algorithms
topological-sort DAG ordering dependencies

Core Idea

Topological sort produces a linear ordering of vertices in a directed acyclic graph (DAG) such that for every directed edge u → v, u appears before v. It is only possible for DAGs — any graph with a cycle has no valid topological ordering. Two standard algorithms are DFS-based (append each node to a result stack on DFS finish, then reverse) and Kahn's algorithm (iteratively remove nodes with in-degree zero using a queue). Topological sort is essential for scheduling problems, build systems, and resolving dependency chains.

How It's Best Learned

Implement both the DFS-based approach and Kahn's algorithm. Apply both to a concrete dependency problem such as course prerequisite ordering. Verify that Kahn's algorithm detects cyclic graphs by checking whether all nodes appear in the output.

Common Misconceptions

Explainer

You already understand directed graphs and depth-first search. Now consider a practical problem: you have a list of tasks, and some tasks must be completed before others. Course prerequisites are a perfect example — you cannot take Data Structures before Introduction to Programming. Topological sort takes a directed acyclic graph (DAG) of such dependencies and produces a linear ordering where every task appears after all of its prerequisites. It answers the question: "in what order can I do everything, respecting all the constraints?"

The DFS-based algorithm leverages a property you know from depth-first search: when DFS finishes processing a node (all its descendants have been fully explored), that node has no unvisited dependencies remaining in its subtree. By recording each node's finish time — the moment DFS completes it — and then reversing the order, you get a valid topological sort. Intuitively, nodes that other nodes depend on will finish later in DFS (because DFS must first finish all their descendants), so reversing finish order places prerequisites first. In practice, you push each node onto a stack when DFS finishes it, then pop the stack to get the sorted order.

Kahn's algorithm takes the opposite approach: instead of going deep, it works from the "outside in." Start by finding all nodes with in-degree zero — nodes that have no prerequisites. These can safely go first. Add them to a queue, and for each one you process, remove its outgoing edges (decrement the in-degree of its neighbors). Any neighbor whose in-degree drops to zero gets added to the queue. Repeat until the queue is empty. The order in which nodes are dequeued is a valid topological sort. A powerful bonus: if the queue empties before all nodes are processed, the remaining nodes are part of a cycle, so Kahn's algorithm doubles as a cycle detector.

Both algorithms run in O(V + E) time — linear in the size of the graph — because each vertex and edge is processed exactly once. The choice between them is mostly stylistic: DFS-based is natural when you already have DFS infrastructure, while Kahn's is often easier to reason about and naturally yields cycle detection. Topological sort is foundational beyond course scheduling. Build systems like Make use it to determine compilation order. Package managers use it to resolve installation dependencies. Spreadsheet engines use it to determine cell recalculation order. And in algorithm design, topological sort enables efficient dynamic programming on DAGs — once you have a valid ordering, you can process nodes left to right, and every node's dependencies are guaranteed to have been computed already.

Practice Questions 5 questions

Prerequisite Chain

Understanding Zero → The Number Zero → Counting to Five → Counting to 10 → Counting to 20 → Counting a Set of Objects Up to 20 → Cardinality: The Last Number Counted → Matching Numerals to Quantities → Subitizing Small Quantities → Addition Within 10 → Number Bonds to 10 → Addition Within 20 → Doubles and Near Doubles → Doubles Facts Within 10 → Near Doubles Facts Within 20 → Mental Math Strategies for Addition → Mental Math: Adding and Subtracting Tens → Addition Within 100 → Repeated Addition as Multiplication → Multiplication as Equal Groups → Multiplication: Arrays → Basic Multiplication Facts (0s, 1s, 2s, 5s, 10s) → Multiplication Facts Within 100 → Division as Equal Sharing → Division as Grouping (Measurement Division) → Division: Grouping (Repeated Subtraction) Model → Division: Fair Sharing Model → Division as Equal Sharing → Division as Grouping → Basic Division Facts → Division Facts Within 100 → Multiplication and Division Fact Families → Relationship Between Multiplication and Division → Division Facts as Inverse of Multiplication → Remainders and Quotients in Division → Division Word Problems → Multi-Step Word Problems → Solving Multi-Step Word Problems → Multiplication Word Problems → Division Word Problems → Introduction to Long Division → Factors and Multiples → Prime and Composite Numbers → Equivalent Fractions → Relating Fractions and Decimals → Decimal Place Value → Integers and the Number Line → Comparing and Ordering Integers → Absolute Value → Adding Integers → Subtracting Integers → Multiplying Integers → Introduction to Exponents → Order of Operations → Integer Order of Operations → Variable Expressions → The Distributive Property → Variables and Expressions Review → Introduction to Polynomials → Adding and Subtracting Polynomials → Multiplying Polynomials → Factorial → Permutations → Combinations → Counting Principles: Addition and Multiplication Rules → Introduction to Graph Theory → Propositional Logic Foundations → Logical Equivalences → Boolean Algebra → Boolean Type and Truth Values → Comparison Operators and Boolean Tests → Logical Operators and Boolean Algebra → Conditional Statements → Defining and Calling Functions → Functions: Decomposing Problems → Function Parameters and Argument Passing → Return Values → Variable Scope → Introduction to Classes → Objects and Instances → Methods and Attributes → Algorithm Design Basics → Tree Structure and Node Properties → Binary Trees → Tree Traversals → Depth-First Search (DFS) → Depth-First Search: Implementation and Applications → Topological Sort

Longest path: 88 steps · 443 total prerequisite topics

Prerequisites (5)

Leads To (2)