Graph traversal · Medium
A network report groups nodes that are connected when link direction is ignored. It needs the sizes of every group, ordered largest first, including isolated nodes. Repeated links do not create more members and group labels are not part of the output.
Return the sizes of all weakly connected components in descending numeric order while counting each declared node exactly once.
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 nodes; edges contains [from,to] pairs whose direction is ignored for connectivity.
- Parallel edges and self-loops are allowed. Nodes without edges still exist.
Output
Return value
- Return a descending array of component sizes; equal sizes appear separately.
- An empty graph returns []; each isolated node contributes one.
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
],
[
2,
3
],
[
3,
4
]
],
"n": 6
}Returns
[
3,
2,
1
]Example 2
{
"edges": [],
"n": 3
}Returns
[
1,
1,
1
]Required complexity
O(n + m + c log c) time and O(n + m) space for c components