Same setting as Course schedule, but return one valid order of all courses, or an empty array if it is impossible.
Before you code
Kahn's algorithm already produces the order as it runs; the only extra step is returning it, or nothing if it came out short.
Hints
- Same graph and in-degrees as before.
- Append each dequeued course to the order.
- If the order has fewer than numCourses entries, return [].
- Try the DFS version too: reverse the finish order, and raise on a gray neighbor.
Production & complexity notes
When solving Course schedule II on LeetCode (medium), always state your loop or recursion invariant before writing code. Verify how your chosen data structure behaves on degenerate inputs (single-element inputs, all-duplicate keys, strictly monotonic sequences, or maximum constraint sizes up to $10^5$ elements). In production interviews, pair your implementation with an explicit time and auxiliary space complexity proof, explain why alternative brute-force approaches violate the latency budget, and trace how cache locality and memory allocation overhead affect wall-clock throughput on real hardware. Review the step-by-step memory trace in Topological sort to reinforce the underlying pattern.
What it practices
Producing a topological order, from Topological sort.