Union-Find (Disjoint Set)
Master the Union-Find data structure. Essential for Kruskal's Algorithm, connected components, and cycle detection in undirected graphs.
Union-Find (Disjoint Set)
Master the Union-Find data structure. Essential for Kruskal's Algorithm, connected components, and cycle detection in undirected graphs.
union(x, y)
Order the steps of union by rank with path compression.
Tap a piece, then tap where it goes — or drag it. Tap the tray to take one back.
- 1Drop a step here
- 2Drop a step here
- 3Drop a step here
- 4Drop a step here
Test your knowledge
What is the primary optimization that makes Union-Find nearly constant time?
Write the code
Number of Provinces
The short version
Think of social networks. When person A befriends person B, their entire groups of friends merge into one giant community. You can quickly check if two random people are in the same extended network.
In more depth
Disjoint Sets
Union-Find is a data structure that tracks a set of elements partitioned into a number of disjoint (non-overlapping) subsets.
Operations:
Optimizations:
When to reach for this
- Find connected components in a graph
- Check if two nodes are connected (fast)
- Cycle detection in undirected graphs
- Kruskal's Algorithm for MST
Interview Questions
Love this visualization?
Sign up to track your progress, earn achievements, use the AI assistant, and access your personal learning dashboard.
100% free • No credit card required