mediumGraphGraphs

Topological Sort

mediumTime: O(V+E)Space: O(V+E)

Signals to notice

order elements respecting dependenciesno element before its prerequisitesDAG linearization

Brute force first

Try all permutations and check validity. Brute-force ordering. That instinct is useful because it follows the prompt literally, but it usually keeps revisiting work the problem is begging you to organize.

The key insight

Kahn's algorithm (BFS): compute in-degrees, start with in-degree-0 nodes, process and decrement neighbors' in-degrees. Or DFS with post-order reversal. Once you hold onto the right piece of information from moment to moment, the problem feels less like trial and error and more like following a shape that was there all along.

What must stay true

In a topological order, every edge (u,v) means u appears before v. Nodes with in-degree 0 have no unmet prerequisites and can be processed first. When you keep that truth intact, each local choice supports the larger solution instead of fighting it.

Easy way to go wrong

Confusing topological sort with regular sorting — topological sort works on DAGs (no cycles). If the graph has a cycle, no valid topological order exists. When the code becomes mechanical before the idea is clear, small edge cases start breaking the whole story.

Graphs Pattern