Strongly connected components · Hard
A plugin loader needs to show mutually dependent plugins as groups before planning a migration.
Partition a directed graph into strongly connected components.
Input
Call
- Implement
solve(input)and return its result. Do not print fromsolve.
Input object
{ n:integer, edges:[from:integer,to:integer][] }
Input rules
- Duplicate and self-edges are allowed.
What each field means
n— number of nodes, identified by0throughn - 1.- Each
[from, to]inedgesis a directed dependency.
Output
Return value and rules
- Group nodes that can all reach one another through directed paths.
- Return every node exactly once, including isolated nodes.
- Sort IDs inside each group, then sort groups by their smallest ID.
Constraints
- 0 <= n <= 100000; 0 <= edges.length <= 200000
- Every vertex 0..n-1 must appear, including isolated vertices. Avoid recursion proportional to n.
Examples
Example 1
{
"edges": [
[
0,
1
],
[
1,
0
],
[
1,
2
],
[
2,
3
],
[
3,
2
]
],
"n": 4
}Returns
[
[
0,
1
],
[
2,
3
]
]Example 2
{
"edges": [],
"n": 0
}Returns
[]Required complexity
O(n log n + m) time and O(n + m) space