Union Find | Disjoint Set Union Introductory Problem
Prereq: Depth First Search Review
Now we will start with an introductory problem to get you familiar with the data structure. Complete the class below to support the following two operations:
merge(x, y)
merges the sets to whichx
andy
belong,is_same(x, y)
determines ifx
andy
belong to the same set. If so returntrue
, otherwisefalse
.
Example:
merge(1, 2)
merge(2, 3)
is_same(1, 3) => true
is_same(2, 4) => false
Explanation:
We merge elements 1
and 2
then we merge the set of 1
and 2
with the element 3
,
so we should now have 2 sets: [1, 2, 3]
and [4]
.
Therefore 1
and 3
are in the same set, while 2
and 4
are in different sets.
Try it yourself
xxxxxxxxxx
class SameSet:
def merge(self, x: int, y: int) -> None:
# WRITE YOUR BRILLIANT CODE HERE
pass
​
def is_same(self, x: int, y: int) -> bool:
# AND HERE
return False
​
if __name__ == "__main__":​
​
Solution
Title
Script
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem
Ipsum
has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.
Contrary to popular belief, Lorem
Ipsum
is not simply random text.
>>> a = [1, 2, 3] >>> a[-1] 3
xxxxxxxxxx
from typing import List
def testFunction(arr: List[int], target) -> int:
# WRITE YOUR BRILLIANT CODE HERE
​
if __name__ == '__main__':​
​
Get AlgoMonster Pro for instant access to all content and solutions