Union-Find (Disjoint Set) Data Structure

beginner
24 min

Union-Find (Disjoint Set) Data Structure

Welcome to our deep dive into the Union-Find (Disjoint Set) Data Structure! This powerful tool is a must-know for anyone looking to conquer algorithms and data structures. Let's explore this concept together, step by step, with real-world examples.

What is Union-Find? šŸŽÆ

Union-Find, also known as Disjoint Set Union, is a data structure used to represent a partition of a set into disjoint subsets of equivalent objects. It allows you to perform two primary operations:

  1. Union: Combine two disjoint sets into one.
  2. Find: Determine which set a particular element belongs to.

Why use Union-Find? šŸ“

Union-Find is essential in various applications, such as:

  • Clustering: Grouping similar objects together.
  • Kruskal's Algorithm: For finding the minimum spanning tree in a graph.
  • Dependency Analysis: In compilers, to determine the order of compilation of source files.

Understanding the Union-Find Data Structure šŸ’”

Sets and Connections

Initially, each element in the set is a separate set with a single element. As we perform union operations, sets are combined, and connections between them are established.

Example:

python
elements = [0, 1, 2, 3, 4, 5] sets = [None] * len(elements) # Initially, each element is its own set for i in range(len(elements)): sets[i] = i

Finding the Root

To find the root of a set, we keep track of a parent pointer for each element. The root of a set is the element that does not have a parent.

python
def find_root(element): if sets[element] != element: sets[element] = find_root(sets[element]) return sets[element]

Unioning Sets

When we union two sets, we make the root of one set a child of the other set's root. This creates a path from the element in the smaller set to the root of the larger set.

python
def union(set1, set2): root1 = find_root(set1) root2 = find_root(set2) if root1 < root2: sets[root2] = root1 else: sets[root1] = root2

Practice Time šŸ’”

Let's put our knowledge to the test!

Quick Quiz
Question 1 of 1

What is the main purpose of the Union-Find data structure?

Quick Quiz
Question 1 of 1

In Union-Find, what is the purpose of the parent pointer?