The Course Schedule II interview question is an extension of the first Course Schedule problem. Instead of just saying if it's possible to finish all courses, you must return the actual order in which the courses should be taken. If it is impossible to finish all courses due to a cycle, you return an empty array.
Companies like Uber, LinkedIn, and Palantir ask this Topological Sort coding problem to see if you can not only detect dependencies but also produce a valid linear ordering. It tests your ability to manage state (the resulting schedule) during a graph traversal. It’s a very common real-world problem used in package managers (like npm or pip) and build systems (like Make or Bazel).
The problem uses Topological Sort.
Courses: 4, Prerequisites: [[1,0],[2,0],[3,1],[3,2]]
[0, 1, 2, 3] (or [0, 2, 1, 3]).result.size() == numCourses.Topological sort is only possible if the graph is a DAG (Directed Acyclic Graph). If the interviewer asks for the "lexicographically smallest" order, you should use a Priority Queue instead of a regular Queue in Kahn's algorithm.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Course Schedule | Medium | Solve | |
| Minimum Height Trees | Medium | Solve | |
| Course Schedule IV | Medium | Solve | |
| Find Eventual Safe States | Medium | Solve | |
| All Ancestors of a Node in a Directed Acyclic Graph | Medium | Solve |