Algo-Sim › Advanced Graphs
Number of Connected Components (Union-Find)
Medium · Advanced Graphs · step through it in Java, Python and C++ on your own input
Count the pieces of an undirected graph with union-find: start with n sets and subtract one for every edge that joins two of them.
Problem
Given n nodes labelled 0..n − 1 and a list of undirected edges, return the number of connected components: groups of nodes that are joined to each other by paths and to nothing else. Here the edges are processed one at a time, as if they arrived in a stream.
Constraints
- 1 ≤ n ≤ 2000
- 0 ≤ edges.length ≤ 5000
- No self-loops or repeated edges
Edge cases to test
- No edges: n
- Duplicate edges
- Every node joined
Follow-up questions
- Why path compression and union by rank?
- Together they make each operation O(α(n)), effectively constant.
- When is union-find better than DFS?
- When edges arrive online, or when you only need to know whether two nodes are connected.
Solution
Java
public int countComponents(int n, int[][] edges) {
int[] parent = new int[n];
for (int i = 0; i < n; i++) parent[i] = i;
int components = n;
for (int[] e : edges) {
int a = find(parent, e[0]), b = find(parent, e[1]);
if (a != b) {
parent[a] = b;
components--;
}
}
return components;
}
private int find(int[] parent, int x) {
while (parent[x] != x) {
parent[x] = parent[parent[x]];
x = parent[x];
}
return x;
}Python
def count_components(n, edges):
parent = list(range(n))
components = n
for u, v in edges:
a, b = find(parent, u), find(parent, v)
if a != b:
parent[a] = b
components -= 1
return components
def find(parent, x):
while parent[x] != x:
parent[x] = parent[parent[x]]
x = parent[x]
return xC++
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int countComponents(int n, vector<vector<int>> &edges) {
vector<int> parent = vector<int>(n);
for (int i = 0; i < n; i++)
parent[i] = i;
int components = n;
for (vector<int> &e : edges) {
int a = find(parent, e[0]), b = find(parent, e[1]);
if (a != b) {
parent[a] = b;
components--;
}
}
return components;
}
int find(vector<int> &parent, int x) {
while (parent[x] != x) {
parent[x] = parent[parent[x]];
x = parent[x];
}
return x;
}
};
More Advanced Graphs problems
- Network Delay Time (Medium)
- Evaluate Division (Medium)
- Course Schedule II (Medium)
- Alien Dictionary (Hard)
- Redundant Connection (Medium)
- Accounts Merge (Medium)
- Minimum Spanning Tree (Kruskal) (Medium)
- Minimum Spanning Tree (Prim) (Medium)
- Min Cost to Connect All Points (Medium)
- Cheapest Flights Within K Stops (Medium)
- Bellman-Ford (negative weights) (Medium)
- Find the City (Floyd-Warshall) (Medium)
- Critical Connections in a Network (Hard)
- Articulation Points (Cut Vertices) (Hard)
- Strongly Connected Components (Hard)
- Reconstruct Itinerary (Hard)
- Minimum Height Trees (Medium)