java
48 lines · 7 steps
How union-find with path compression works
A disjoint-set structure that tracks connected groups using union by rank and path compression for near-constant lookups.
Explained by
highlit
1public class UnionFind {
2 private final int[] parent;
3 private final int[] rank;
4 private int count;
5
6 public UnionFind(int n) {
7 parent = new int[n];
8 rank = new int[n];
9 count = n;
10 for (int i = 0; i < n; i++) {
11 parent[i] = i;
12 }
13 }
14
15 public int find(int x) {
16 while (parent[x] != x) {
17 parent[x] = parent[parent[x]]; // path compression
18 x = parent[x];
19 }
20 return x;
21 }
22
23 public boolean union(int a, int b) {
24 int rootA = find(a);
25 int rootB = find(b);
26 if (rootA == rootB) {
27 return false;
28 }
29 if (rank[rootA] < rank[rootB]) {
30 parent[rootA] = rootB;
31 } else if (rank[rootA] > rank[rootB]) {
32 parent[rootB] = rootA;
33 } else {
34 parent[rootB] = rootA;
35 rank[rootA]++;
36 }
37 count--;
38 return true;
39 }
40
41 public boolean connected(int a, int b) {
42 return find(a) == find(b);
43 }
44
45 public int count() {
46 return count;
47 }
48}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Representing each set by a root element lets you test membership by comparing roots.
- 2Path compression and union by rank together keep operations nearly constant time.
- 3Tracking a count field gives you the number of distinct groups for free.
Related explainers
java
public interface GitHubClient { @GetExchange("/users/{username}") GitHubUser getUser(@PathVariable String username);
Declarative HTTP clients in Spring
http-client
declarative-api
proxy
Intermediate
8 steps
java
import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map;
Building a trie for autocomplete in Java
trie
prefix-tree
recursion
Intermediate
8 steps
java
@RestController @RequestMapping("/api/products") public class ProductSearchController {
Binding collection query params in Spring
rest-api
query-parameters
dependency-injection
Intermediate
6 steps
go
package scheduler import ( "container/heap"
A priority job queue with Go's container/heap
priority-queue
heap
interfaces
Intermediate
9 steps
java
import java.util.ArrayDeque; import java.util.Deque; import java.util.Map;
Evaluating math expressions with two stacks
stacks
parsing
operator-precedence
Intermediate
9 steps
java
@Entity @Table(name = "orders") @SQLDelete(sql = "UPDATE orders SET deleted = true, deleted_at = now() WHERE id = ?") @Where(clause = "deleted = false")
Soft deletes with Hibernate in Spring
soft-delete
jpa
hibernate
Intermediate
9 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/how-union-find-with-path-compression-works-explained-java-01b6/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.