Union find Flashcards
(9 cards)
What is the definition of Union Find?
Tracks disjoint sets with union and find operations.
When is Union Find used?
Used for connected components and cycle detection.
What is an example use case for Union Find?
Number of Provinces.
What are the key steps in Union Find?
- Initialize parent array for each node.
- Find: Get root with path compression.
- Union: Merge sets by rank.
How does Union Find apply to Number of Provinces?
Count connected provinces in graph by unioning connected cities and counting distinct roots.
What is the complexity of Union Find?
Time: O(α(n)) per operation, Space: O(n).
What are some gotchas with Union Find?
Disconnected graph and self-loops.
Provide a code example for Union Find.
```python
from typing import List
class UnionFind:
def __init__(self, size: int) -> None:
self.parent = list(range(size))
self.rank = [0] * size
self.count = size
def find(self, x: int) -> int:
if self.parent[x] != x:
self.parent[x] = self.find(self.parent[x])
return self.parent[x]
def union(self, x: int, y: int) -> None:
px, py = self.find(x), self.find(y)
if px == py:
return
if self.rank[px] < self.rank[py]:
px, py = py, px
self.parent[py] = px
if self.rank[px] == self.rank[py]:
self.rank[px] += 1
self.count -= 1
def find_circle_num(is_connected: List[List[int]]) -> int:
n = len(is_connected)
uf = UnionFind(n)
for i in range(n):
for j in range(i + 1, n):
if is_connected[i][j]:
uf.union(i, j)
return uf.count
~~~
What visual aids can be used for Union Find?
Sketch union operations on paper.