Topological sort · Medium
A course scheduler receives prerequisites that must be completed before another course. It needs to know whether any valid completion order exists. The output is feasibility only, not the order itself.
Return whether all n courses can be completed without violating any prerequisite relationship.
Input
Call
- Implement solve(input) and return the result. The provided adapter handles JSON input and output.
Input shape
A JSON object { "n": number, "prerequisites": [number, number][] }.
Fields
- n is the number of vertices with IDs 0..n-1. Every endpoint is valid. Parallel edges and self-edges are allowed; when n is 0 the edge list is empty.
- prerequisites contains [course,prerequisite] pairs: the second must finish before the first.
Output
Return value
- Return false exactly when the directed graph contains a cycle.
- Repeated pairs do not change feasibility. A course requiring itself makes the answer false.
- No courses or no prerequisites is feasible.
Constraints
- 0 <= n <= 100000 and at most 200000 edges.
- A chain may contain 100000 vertices; do not depend on a call stack that deep.
Examples
Example 1
{
"n": 3,
"prerequisites": [
[
1,
0
],
[
2,
1
]
]
}Returns
true0 then 1 then 2 works.
Example 2
{
"n": 2,
"prerequisites": [
[
0,
1
],
[
1,
0
]
]
}Returns
falseNeither can finish first.
Required complexity
O(n + m) time and space