Count Non-Connected Subsystems
Problem
Given n entities in a system and m relationships between pairs of them, find how many non-connected subsystems exist — i.e. the number of connected components in the resulting graph.
Input / Output
- Input: integer
n(entities labelled0 .. n-1or1 .. n) and a list ofmrelationship pairs. - Output: the number of connected components.
Constraints
- Relationships are undirected.
- Up to ~10^5 entities and relationships.
- Duplicate edges and self-loops may appear and must not affect the count.
Example
- Entities
{1,2,3,4,5}, relationships{(1,2),(2,3),(4,5)}→2components:{1,2,3}and{4,5}. - Tricky case: an entity with no relationships at all is still its own component — so
n=3with zero edges →3. Solutions that iterate over edges rather than nodes routinely miss isolated entities.
asked …