Course Order and Cycle
Problem statement
There are numCourses courses numbered from 0 through numCourses - 1. Each row [course, prerequisite] means the prerequisite must be completed before the course.
Return a two-row result [order, cycle]:
- If all courses can be completed, return the lexicographically smallest valid topological order in
orderand an emptycycle. - If completion is impossible, return an empty
orderand one directed cycle incycle. Do not repeat the first course at the end.
To make cycle selection deterministic, inspect starting courses in increasing order and each course's outgoing neighbors in increasing order. Return the active-path segment closed by the first back edge encountered.
Function
analyzeCourses(numCourses: int, prerequisites: int[][]) → int[][]Examples
Example 1
numCourses = 4prerequisites = [[1,0],[2,0],[3,1],[3,2]]return = [[0,1,2,3],[]]Course 0 is first. Courses 1 and 2 then become available, and the smaller course is chosen first.
Example 2
numCourses = 3prerequisites = [[1,0],[2,1],[0,2]]return = [[],[0,1,2]]The directed edges form 0 -> 1 -> 2 -> 0, so no topological order exists.
Constraints
1 <= numCourses <= 10^5.0 <= prerequisites.length <= 2 * 10^5.- Every prerequisite row contains two distinct valid course numbers.
- No prerequisite edge appears more than once.