Introduction
You might have listened about the disjoint sets in mathematics where the intersection of two sets results in a null value. In our programming world, disjoint sets or merge–find set is a data structure that stores a collection of disjoint (non-overlapping) sets.
Disjoint sets are used to detect whether a graph contains the cycle or not, which means it finds the connected components in the graph. Union-Find Algorithm(union by rank and path compression) can be used to check whether an undirected graph has a cycle or not.
In this problem, we will be using this concept. Let’s see how and what the problem states.
Problem Statement
We are given an array of ‘arr,’ where each arr[i] = [time, idA, idB] has a non-negative integer ‘time’ and the ‘ids’ of two different people. ‘N’ people have unique ids ranging from 0 to N-1.
Each ‘arr’ represented when two different people became friends.
If A is a friend with B, or A is a friend with someone acquainted with B, then we aim to return the earliest time every person became acquainted with every other person.
Note:
- The ids are 0-indexed.
- Friendship is symmetric here. If A is friends with B, then B is friends with A.
We will see this with the help of an example for more clarity.
Example1:
Input: N = 4, arr[] = {{2, 0, 1}, {3, 1, 2}, {4, 2, 3}}
Starting id from ‘0’ to ‘N-1’ i.e the number of people are 0,1,2,3.
- At time = 2, {0} and {1} became friends. Group of people become= {0, 1}, {2}, {3}.
- At time = 3, {1} and {2} became friends. Group of people become= {0, 1, 2}, {3}.
- At time = 4, {2} and {3} became friends. Group of people become= {0, 1, 2, 3}.
The circle gets completed, and the time is 4 because 4 is the largest time to complete a circle.
Output:
4
Example2:
Input: arr=[[201,0,1],[209,3,4],[207,2,3],[208,1,5],[202,2,4],[203,0,3],[200,1,2],[206,4,5]],
N = 6
Output: 203
Explanation:
- At time = 201,{0} and {1} become friends and group of people become= {0,1}, {2}, {3}, {4}, {5}.
- At time = 209,{3} and {4} become friends and group of people become= {0,1}, {2}, {3,4}, {5}.
- At time = 207,{2} and {3} become friends, and group of people become= {0,1}, {2, 3, 4}, {5}.
- At time = 208,{1} and {5} become friends, and group of people become= {0,1,5}, {2,3,4}.
- At time = 202,{2}, and {4} are already friend.
- At time = 203,{0} and {3} have become friends, and that is what we want so that the output will be ‘203’.




