Disjoint Set Union (DSU), also known as Union-Find, is a data structure used to efficiently manage a collection of non-overlapping (disjoint) sets.
It helps us answer two fundamental questions:
- Find: Which set does an element belong to?
- Union: Can we combine two sets into a single set?
Example: Railway Network Connectivity
Imagine a railway authority managing a railway network consisting of multiple train stations distributed across different cities.
The railway connections are progressively added. The railway authority wants to maintain information about which stations belong to the same interconnected railway network. This helps answer connectivity queries like "Can a passenger travel between two given stations?"
add visualization here...
The key observation is that if a passenger can travel from station A to station B, and from station B to station C, then the passenger can also travel from A to C. Therefore, even if two stations don't have a direct railway connection, they can still belong to the same interconnected railway network.
Design Rationale
In our railway example, each set represents an interconnected railway network.
-
Whenever a new railway connection is established between two stations belonging to different networks, we merge their sets using
union(). -
When we need to determine whether two stations belong to the same network, we compare their representatives using
find().
Implementation