Topological sort · Medium
Application modules initialize in dependency batches. Modules in the same batch may start together, but none may depend on another in that batch.
Return earliest possible batches sorted numerically within each batch, or null for a cycle.
Input
Call
- Implement
solve(input)and return its result. Do not print fromsolve.
Input object
{ n:integer, dependencies:[before:integer,after:integer][] }
Input rules
- Duplicate dependencies are allowed.
What each field means
n— number of modules with IDs0throughn - 1.- Each
[before, after]dependency means thatbeforemust finish in an earlier batch.
Output
Return value and rules
- Return the earliest possible batch for every module, as an array of arrays.
- Sort module IDs numerically within each batch.
- Return
nullfor a dependency cycle, or[]when there are no modules.
Constraints
- 0 <= n <= 10000; 0 <= dependencies.length <= 100000
- Endpoints are valid; a self-edge is a cycle.
Examples
Example 1
{
"dependencies": [
[
0,
2
],
[
1,
2
],
[
2,
3
]
],
"n": 4
}Returns
[
[
0,
1
],
[
2
],
[
3
]
]Example 2
{
"dependencies": [],
"n": 0
}Returns
[]Required complexity
O(n log n + m) time and O(n + m) space