Courses / DSA Patterns for Working Engineers / Chapter 16
Module 5 · Cyclic sort, topological sort, and sort and search · Chapter 16 of 39
Topological Sort: Ordering Tasks by Their Dependencies
Builds on The Coding Interview: How the Round Runs and How to Prepare. Next up: Sort and Search: Sort Once, Then Search Fast.
Part 1 · Introduction to topological sort
Tasks that wait for each other
A build tool must compile a package before the packages that import it, and a course planner must place a prerequisite before the course that needs it. Both ask for a line of items in which every item comes after the items it waits for.
Draw each item as a node and each wait as an arrow: an arrow from u to v means u comes before v. This is a directed graph, nodes joined by one-way edges. A topological order lists every node so that each edge points forward, and finding one is a topological sort. The running example is seven made-up packages.
| Package | Needs first |
|---|---|
| core | nothing |
| log, net, auth | core |
| http | log and net |
| api | http and auth |
| app | api |