Course Schedule II
Medium
Topics
There are n courses labelled 0 to n - 1. You are given edges where edges[i] = [a, b] means you must take course a before course b.
Return the length of a valid ordering in which all courses can be finished, or 0 if no such ordering exists.
The original problem returns the ordering itself. Because many orderings are valid, this judge asks for the length of the order you build — which is n exactly when a full topological sort succeeds, and 0 when a cycle blocks it. Build the real array, then return its length.
Example 1
Input: n = 4, edges = [[1,0],[2,0],[3,1],[3,2]] Output: 4 Explanation: One valid order is [3,1,2,0], so the length is 4.
Example 2
Input: n = 2, edges = [[0,1],[1,0]] Output: 0 Explanation: The two courses depend on each other, so no ordering exists.
Constraints
- 1 <= n <= 2000
- 0 <= edges.length <= 5000
- edges[i].length == 2
- All pairs are distinct
Run ⌘' · Submit ⌘⏎