Produce a Deterministic Course Plan
RobinhoodSoftware Engineer · OnsiteLast updated
Return the lexicographically smallest valid course order from prerequisite pairs, or report a cycle. Handle duplicate edges, malformed IDs, self-dependencies, empty course sets, and large graphs with deterministic topological sorting.
Produce a Deterministic Course Plan
There are num_courses courses numbered 0 through num_courses - 1. Each prerequisite pair is [course, prerequisite], meaning prerequisite must appear before course.
def prerequisite_plan(
num_courses: int,
prerequisites: list[list[int]]
) -> list[object]:
...
Return [true, order] if every course can be completed, where order is the lexicographically smallest valid list of all course IDs. Return [false, []] if the requirements contain a cycle. Duplicate prerequisite pairs do not change the result.
Constraints and Boundary Rules
- 0 <= num_courses <= 200000
- 0 <= len(prerequisites) <= 400000
- Every pair must contain exactly two integer IDs in range.
- Self-dependencies are cycles.
- For num_courses == 0, return [true, []].
- Malformed pairs or out-of-range IDs must raise ValueError.
- Inputs and outputs are JSON-marshalable and outputs are compared exactly.
Examples
Input: num_courses = 4
prerequisites = [[1, 0], [2, 0], [3, 1], [3, 2]]
Output: [true, [0, 1, 2, 3]]
Input: num_courses = 2
prerequisites = [[1, 0], [0, 1]]
Output: [false, []]
Input: num_courses = 3
prerequisites = []
Output: [true, [0, 1, 2]]
Hints
- Model what makes a course eligible at any moment.
- The ordinary valid-order problem does not choose between simultaneous options; the requested output does.
- Ensure duplicate edges do not distort eligibility.
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.