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
@Component @Converter public class EncryptedStringConverter implements AttributeConverter<String, String> {
Transparent column encryption in Spring & JPA
encryption
aes-gcm
jpa-converter
Advanced
10 steps
java
package com.acme.billing.config; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.context.properties.ConfigurationProperties;
Feature-flagged beans with Spring @ConditionalOnProperty
feature-flags
conditional-beans
strategy-pattern
Intermediate
5 steps
java
public static Map<String, String> parseCookieHeader(String header) { Map<String, String> cookies = new LinkedHashMap<>(); if (header == null || header.isBlank()) { return cookies;
Parsing an HTTP Cookie header in Java
string-parsing
http
url-decoding
Intermediate
6 steps
java
public class TimedSocketReader { private static final int READ_TIMEOUT_MS = 5_000; private static final int CONNECT_TIMEOUT_MS = 3_000;
Reading a socket with connect and read timeouts
sockets
timeouts
io
Intermediate
8 steps
java
public final class EncodingDetector { public enum Encoding { UTF_8, UTF_16LE, UTF_16BE, UTF_32LE, UTF_32BE, ASCII, UNKNOWN
Detecting text encoding from raw bytes in Java
byte-manipulation
encoding-detection
bitwise-operations
Intermediate
8 steps
java
public final class ImportOrganizer { private static final Pattern IMPORT_LINE = Pattern.compile("^import\\s+(static\\s+)?([\\w.]+(?:\\.\\*)?)\\s*;\\s*$");
Sorting Java imports with a regex pass
regex
sorting
text-processing
Intermediate
8 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.