Challenge
Vertices are labelled 0 through n-1. Each [u, v] edge connects both directions. Return the number of connected components, counting isolated vertices as components too. Self-loops and duplicate edges do not join otherwise separate components.
Input and output contract
0 ≤ n ≤ 30,000; 0 ≤ edge count ≤ 60,000; all endpoints are valid vertex indices. If n=0, edges is empty and the answer is 0.
All tests follow this contract. You do not need to validate malformed input. Return the requested result from connected_components; printed output is not your answer. Standard-library tools are allowed. Implement your solution in Python 3.12.
Target complexity: O(n + e) time and auxiliary space
Return values are checked by type. Use the exact function name. Print output is not your answer. Tests have time and memory limits.
Public examples
Arguments
[6, [[0, 1], [1, 2], [3, 4], [4, 3], [5, 5]]]
Expected return
3
Arguments
[3, []]
Expected return
3
Arguments
[0, []]
Expected return
0
Hint
Start a traversal from every vertex not yet visited. Count starts, not edges.
The worked solution unlocks after completion, or with Premium access.