hardGraphsGraphs

Course Schedule II

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

Recognize the pattern

find a valid ordering of all coursesreturn the actual ordertopological sort

Brute force idea

A straightforward first read of Course Schedule II is this: 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.

Better approach

The real unlock in Course Schedule II comes when you notice this: 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.

Key invariant

The compass for Course Schedule II is this: 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.

Watch out for

One easy way to drift off course in Course Schedule II is this: 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