Count Non-Connected Subsystems in an Entity Relationship Graph
viaLeetCode
Problem: Given n entities in a system and m relationships (edges) between pairs of entities, find how many non-connected subsystems (connected components) there are.
Constraints: n entities, m relationships, treat relationships as undirected edges.
Example: entities {1,2,3,4,5}, relationships {(1,2),(2,3),(4,5)} -> 2 connected components: {1,2,3} and {4,5}.
Approach: Model entities as graph nodes and relationships as edges. Use Union-Find (Disjoint Set Union) or BFS/DFS to find connected components: union each pair of related entities, then count the number of distinct root parents (or count unvisited BFS/DFS traversals). O(n + m) with DSU using path compression and union by rank.
asked …