Intermediate Topic 31 of 52 Data Structures
Path Compression
Flattening find paths to speed up disjoint sets.
How it works
Path compression is an optimization in union-find: during a find operation, every node visited on the way to the root is re-pointed directly at the root, flattening the tree. Future finds on those nodes take one step. Combined with union by rank, it yields amortized time per operation of the inverse Ackermann function, effectively constant.
Step-by-step walkthrough
- A long chain d to c to b to root makes find slow.
- find(d) walks the whole chain up to the root.
- It reaches the root.
- Every node on the path is re-pointed directly at the root.
- Later finds on those nodes take one step.
Where it is used
Disjoint set union implementations in Kruskal's algorithm, connectivity queries and online equivalence classes use path compression. It can be written recursively or with an iterative two-pass or halving variant.
Common pitfall
The recursive version may overflow the stack on very deep trees before compression has occurred. Path compression alone does not preserve rank values, so rank is only an upper bound. Be careful to return the root, not only to assign parents, and test on chain-shaped inputs.
Where it fits in the course
Path Compression is topic 31 of 52 in Data Structures, rated Intermediate. It follows Disjoint Set Union. The next topic is Skip Lists.
Practice and explore
- Open the interactive lesson, with a mini quiz.
- Take the Data Structures quiz.
How to study this topic
- Read the explanation above and restate the definition in your own words.
- Open the interactive lesson and answer its mini quiz.
- Read the common pitfall, then write a short example that avoids it.
- Check your understanding in the Data Structures quiz, and revisit the topic if you miss a question.
Frequently asked questions
What is Path Compression?
Where do people use Path Compression?
What is the most common mistake with Path Compression?
What should I learn before this topic?
How can I practice it?
Is Path Compression hard to learn?
How long does it take to learn Path Compression?
Which topics are related to Path Compression?
What should I study after Path Compression?
Related topics
- Disjoint Set Union (Data Structures)
- Skip Lists (Data Structures)
- Adjacency Matrix (Data Structures)
- Bloom Filters (Data Structures)
- Image Compression (Graphics, Vision & Media)