Topological sort · Medium
A build scheduler has a complete batch of jobs and directed prerequisites. Many valid schedules may exist, but reproducibility requires the lexicographically smallest sequence of job labels. A cyclic batch must be rejected instead of returning a partial schedule.
Return the lexicographically smallest ordering that places every prerequisite before its dependent job or null if no complete ordering exists.
Input
Call
- Implement solve(input) and return the result. The provided adapter handles JSON input and output.
Input shape
{ n: integer, edges: [integer, integer][] }
Fields
- n is the number of jobs. Each edge [u,v] requires job u before job v.
- Repeated prerequisite entries are allowed and do not change the allowed schedules.
Output
Return value
- Return every label exactly once in a valid lexicographically smallest ordering, or null for any cycle.
- Choose the smallest currently ready job after each completion, not only from the initially ready set. n = 0 returns [].
Constraints
- 0 <= n <= 100000; 0 <= edges.length <= 200000; every endpoint is a valid node label.
- source and target, when used, are either -1 or valid node labels. Empty graphs use -1.
Examples
Example 1
{
"edges": [
[
0,
1
]
],
"n": 4
}Returns
[
0,
1,
2,
3
]Example 2
{
"edges": [
[
0,
1
],
[
1,
0
]
],
"n": 2
}Returns
nullRequired complexity
O((n + m) log(n + 1)) time and O(n + m) auxiliary space