hardGraphsGraphs

Course Schedule II

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

Signals to notice

find a valid ordering of all coursesreturn the actual ordertopological sort

Brute force first

Try all permutations and check validity. Brute-force permutation with constraint checking. 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

Topological sort with BFS (Kahn's): start with courses having no prerequisites (in-degree 0), process them, reduce neighbors' in-degrees. If all courses are processed, the order is valid. Instead of recomputing the world every time, you preserve just enough context to let the next decision become obvious.

What must stay true

A course can be taken only when all its prerequisites are done. In-degree 0 means all prerequisites are satisfied. Processing these first and updating neighbors' in-degrees simulates the natural ordering. As long as that statement keeps holding, you can trust the steps built on top of it.

Easy way to go wrong

Not detecting cycles — if the result has fewer courses than total, there's a circular dependency. Return an empty array, not a partial result. The fix is usually to return to the meaning of each move, not just the steps themselves.

Graphs Pattern