Skip to main content

Disjoint Set

SpaceTime
AccessLookupInsertionDeletion
O(n)O(1)O(n)O(1)O(1)

Definition​

Disjoint Set is a data structure that allows efficient union and find operations on a set of elements.

Simplified

Disjoint Set is like a smart party organizer. It keeps track of distinct groups (like people at a party), can merge groups, and quickly answer if 2 people belong to the same group. It's a way to manage and query non-overlapping groups efficiently.

Practice​

AspectPseudo Code
Disjoint Set Item
get_key():
return value

get_root():
if is_root():
return this
return parent.get_root()

is_root():
return parent == ø

get_rank():
if length of get_children() == 0:
return 0
rank = 0
for each child in get_children():
rank += 1
rank += child.get_rank()
return rank

get_children():
return values of children

set_parent(parent_item, force_setting_parent_child):
parent = parent_item
if force_setting_parent_child == True:
parent_item.add_child(this)

add_child(child_item):
children[child_item.get_key()] = child_item
child_item.set_parent(this, false)
Make Set
make_set(item_value):
disjoint_set_item = DisjointSetItem(item_value, keyCallback)
if items[disjoint_set_item.get_key()] == ø:
items[disjoint_set_item.get_key()] = disjoint_set_item
return this
Find
find(item_value):
template_disjoint_item = DisjointSetItem(item_value, keyCallback)
required_disjoint_item = items[template_disjoint_item.get_key()]
if required_disjoint_item == ø:
return ø
return required_disjoint_item.get_root().get_key()
Union
union(value_a, value_b):
root_key_a = find(value_a)
root_key_b = find(value_b)
if root_key_a == ø or root_key_b == ø:
'One or two values are not in sets'
if root_key_a == root_key_b:
return this
root_a = items[root_key_a]
root_b = items[root_key_b]
if root_a.get_rank() < root_b.get_rank():
root_b.add_child(root_a)
return this
root_a.add_child(root_b)
return this
In Same Set
in_same_set(value_a, value_b):
root_key_a = find(value_a)
root_key_b = find(value_b)
if root_key_a == ø or root_key_b == ø:
'One or two values are not in sets'
return root_key_a == root_key_b