Graph traversal · Medium
A topology snapshot lists devices and undirected connections. Operations needs the number of separately reachable groups, including devices with no connections. This is an in-memory graph snapshot, not a live network probe.
Return how many connected components exist among all n devices after considering every edge.
Input
Call
- Implement solve(input) and return the result. The provided adapter handles JSON input and output.
Input shape
A JSON object { "n": number, "edges": [number, number][] }.
Fields
- n gives the device count. Device IDs are 0 through n - 1.
- edges contains [first,second] undirected connections. Duplicates and self-connections are allowed.
Output
Return value
- Return one integer group count. A path may contain more than one edge.
- Count isolated devices as their own groups.
- Repeated or self-connections never add groups. For n = 0 return 0.
Constraints
- 0 <= n <= 100000 and 0 <= edges.length <= 200000.
- Every endpoint is a valid device ID; when n = 0 edges is empty.
- The input may contain a chain of length 100000. Avoid relying on a call stack that deep.
Examples
Example 1
{
"edges": [
[
0,
1
],
[
1,
2
],
[
3,
3
]
],
"n": 5
}Returns
3The groups are {0,1,2}, {3} and {4}.
Example 2
{
"edges": [],
"n": 3
}Returns
3All three devices are isolated.
Required complexity
O(n + m) time and O(n + m) space for traversal; amortized O((n + m) alpha(n)) time and O(n) space is also accepted