Pattern Recognition Drill
Medium Advanced Graphs
The Problem
Given n courses and prerequisites, return a valid order to take all courses, or empty if impossible.
What approach would you use?
Think about it before scrolling down.
Kahn's BFS: process nodes with in-degree 0. If result has fewer than n nodes, there's a cycle. O(V+E).
DFS with three states (unvisited/in-progress/done). Post-order gives reverse topological order. O(V+E).
Common Trap
Don't forget to detect cycles — if the topological order has fewer than n nodes, return empty.