Union-Find (disjoint-set union)
Connected components, cycle detection in undirected graphs, and Kruskal's algorithm.
High interview relevanceRoadmap: Advanced
| Time | Amortized O(α(n)) per find or union |
|---|---|
| Space | O(n) |
Why it costs this much
Path compression flattens trees on every find, and union by size keeps trees shallow, so long chains cannot persist.
Code
parent = list(range(n))
def find(x):
while parent[x] != x:
parent[x] = parent[parent[x]] # path halving: flatten as we climb
x = parent[x]
return x
def union(a, b):
parent[find(a)] = find(b) # add union by size for the full boundCommon pitfalls
You need both optimizations for the α(n) bound; without them a find can take O(n). Union-Find merges sets but cannot split them.
Operation by operation
| Operation | Best | Average | Worst | Space |
|---|---|---|---|---|
| Union-Find find and union | O(1) | O(α(n)) amortized | O(α(n)) amortized | O(n) |
Union-Find find and union. Union by rank or size, plus path compression. Without both optimizations, a single operation can cost O(n). α(n) is at most 4 for any practical n.