← Topological Sort

Pattern Recognition Drill

#146 — Course Schedule II

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.

Key Signals

Topological Sort

Kahn's BFS: process nodes with in-degree 0. If result has fewer than n nodes, there's a cycle. O(V+E).

Alt: DFS / Recursion

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.

← #145