Union find Flashcards

(9 cards)

1
Q

What is the definition of Union Find?

A

Tracks disjoint sets with union and find operations.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

When is Union Find used?

A

Used for connected components and cycle detection.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What is an example use case for Union Find?

A

Number of Provinces.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What are the key steps in Union Find?

A
  1. Initialize parent array for each node.
  2. Find: Get root with path compression.
  3. Union: Merge sets by rank.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

How does Union Find apply to Number of Provinces?

A

Count connected provinces in graph by unioning connected cities and counting distinct roots.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What is the complexity of Union Find?

A

Time: O(α(n)) per operation, Space: O(n).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What are some gotchas with Union Find?

A

Disconnected graph and self-loops.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Provide a code example for Union Find.

A

```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
~~~

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

What visual aids can be used for Union Find?

A

Sketch union operations on paper.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly