Introduction
Video: https://www.youtube.com/watch?v=0jNmHPfA_yE&t=59s
Chinese Video: https://www.youtube.com/watch?v=VJnUwsE4fWA
Find(x) Find the root/cluster of x. To find which cluster a particular element belongs to find the root of that cluster by following the parent node until a self loop is reached.
Union(x, y) To unify two elements find which are the root nodes of each component and if the root nodes are different, make one of the root nodes be the parent of the other
In this data structure, we don’t “un-union” elements. In general, this would be very inefficient to do since we would have to update all the children of a node.
The number of components is equal to the number of roots remaining.
Map the elements to a array.
[E, F, I, D, C, A, J, L, G, K, B, H]
index 0 1 2 3 4 5 6 7 8 9 10 11
union(C, K) # make K’s root C
0 1 2 3 4 5 6 7 8 4 10 11
Time complexity: O(n) to find the root
- Initialize self-pointing root array
- Union by rank
Optimize: Path Compression Compress the path to make all vertices directly directly points to the root.
Video: https://www.youtube.com/watch?v=VHRhJWacxis
Time Complexity of Look up: O(1) to find the root.
1 | class UnionFind { |
684. Redundant Connection
[Solution] Keep union edges, return the last edge that cannot be added into minimal spanning tree (belongs to the same group -> cycle)
1 | # With the |
Shorter version of union find:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19def findRedundantConnection(self, edges: 'List[List[int]]') -> 'List[int]':
N = len(edges)
parent = [-1] * (N+1)
def find_root(parent, i):
if parent[i] == -1 or parent[i] == i:
parent[i] = i
return i
else:
return find_root(parent, parent[i])
for edge in edges:
x, y = edge
rootx = find_root(parent, x)
rooty = find_root(parent, y)
if rootx != -1 and rootx == rooty:
break
parent[rooty] = rootx
return [x,y]
200. Number of Islands
Leetcode: https://leetcode.com/problems/number-of-islands/
1 |
547. Friend Circles
Leetcode: https://leetcode.com/problems/friend-circles/
1 | def findCircleNum(self, M: List[List[int]]) -> int: |
721. Accounts Merge
Leetcode: https://leetcode.com/problems/accounts-merge/
1 | class DSU(object): |
737. Sentence Similarity II
Leetcode: https://leetcode.com/problems/sentence-similarity-ii/
Note: Beware of the cases when all the words in the first sentence and second sentence are the same, but all of these words are not in pairs
1 | def areSentencesSimilarTwo(self, words1, words2, pairs): |
130. Surrounded Regions
Leetcode: https://leetcode.com/problems/surrounded-regions/
1 | def solve(self, board): |
261. Graph Valid Tree
Leetcode: https://leetcode.com/problems/graph-valid-tree/
Note:
- Keep unioning the nodes on each edge
- If two nodes are already unioned, which means the current edge is an additional edge, and there’s a cycle
- Use
len(edges) == n - 1
to detect any isolated islands
1 | def validTree(self, n, edges): |
Minimal Spanning Tree
Video (Huahua): https://www.youtube.com/watch?v=wmW8G8SrXDs&ab_channel=HuaHua
Kruskal’s Method
Video: https://www.youtube.com/watch?v=JZBQLXgSGfs
Given a graph G = (V, E), we want to find a Minimal Spanning Tree in the graph (may not be unique). A minimum spanning tree is a subset of the edges which connects all vertices in the graph with the minimal edge cost. O(ElogV)
- Sort edges by ascending edge weight
- Walk through the sorted edges and look at the two nodes the edge belongs to, if the nodes are already unified we don’t include this edge, otherwise we include it and unify the nodes
- The algorithm terminates when every edge has been processed or all the vertices have been unified
Prim’s Method
Video: https://www.youtube.com/watch?v=4ZlRH0eK-qQ&ab_channel=AbdulBari
Always select minimum connected edge and expanding the tree starting from the smallest edge. O(ElogV)
1584. Min Cost to Connect All Points
Leetcode: https://leetcode.com/problems/min-cost-to-connect-all-points/
1 | import heapq |
778. Swim in Rising Water
Leetcode: https://leetcode.com/problems/swim-in-rising-water/
Prim’s minimum spanning tree
1 | def swimInWater(self, grid: List[List[int]]) -> int: |
684. Redundant Connection
Leetcode: https://leetcode.com/problems/redundant-connection/
1 | class UnionFind: |