Disjoint Sets / Union Find in Data Structures
Disjoint Sets / Union Find in Data Structures
2
What is a Disjoint Set?
• A disjoint-set data structure (also known as a union-find
data structure) is a specialized data structure that
efficiently represents a collection of disjoint
(non-overlapping) sets.
3
Disjoint Set Operations
• Union: This operation combines two disjoint sets into a single set. It
takes two elements (or their representative elements) from
different sets and merges the sets they belong to.
4
Union Operation – Disjoint Sets
5
Find Operation – Disjoint Sets
6
Find Operation – Disjoint Sets
7
Applications of Disjoint Sets
8
Is B reachable from A?
9
Is B reachable from A?
10
Preprocess Maze – Using Disjoint Data Structure
11
Building a Network
12
Building a Network
13
Building a Network
14
Building a Network
15
Building a Network
16
Building a Network
17
Building a Network
18
Building a Network
19
Building a Network
20
Building a Network
21
Building a Network
22
1. Disjoint Set [Parent-child relationship]
23
1. Disjoint Set [Parent-child relationship]
24
1. Disjoint Set [Parent-child relationship]
25
Disjoint Set Representation
26
Disjoint Set Representation [Linked List
Representation]
[Example 1]
27
Disjoint Set Representation [Linked List
Representation]
[Example 1]
28
Union Operation - Pseudo Code
function union(x, y):
root_x = find(x)
// Find the representative (root) element of set containing 'x‘
root_y = find(y)
// Find the representative (root) element of set containing 'y'
if root_x != root_y:
parent[root_x] = root_y
// 'root_x' and 'root_y' were in different sets, so merge them by making
'root_y' the parent of 'root_x'
return true
// Elements 'x' and 'y' were successfully merged into one set
else:
return false
// Elements 'x' and 'y' were already in the same set
29
Find Operation - Pseudo Code
function find(x):
return parent[x]
// Return the representative element (root) of the set containing 'x'
30
Solved Example
31
Solved Example
32
Solved Example
33
Solved Example
34
End of Topic : Disjoint Sets
Thank You
35