Solution: Longest Consecutive Sequence
Let's solve the Longest Consecutive Sequence problem using the Union Find pattern.
Statement
Given an unsorted array, nums
, your task is to return the length of the longest consecutive sequence of elements. The consecutive sequence of elements is such that there are no missing elements in the sequence. The consecutive elements can be present anywhere in the input array.
Note: Two elements, $x$ and $y$, are called consecutive if the difference between them is equal to $1$.
Constraints:
 $0 \leq$
nums.lengths
$\leq 10^{3}$  $10^{6} \leq$
nums[i]
$\leq 10^{6}$
Solution
So far, you’ve probably brainstormed some approaches and have an idea of how to solve this problem. Let’s explore some of these approaches and figure out which one to follow based on considerations such as time complexity and any implementation constraints.
Naive approach
A naive approach to solve this problem would be to sort the input array and then iterate through the sorted array. For each element, we check if the next consecutive element exists in the sorted array. If it does, we keep incrementing until we reach the end of the sequence. After reaching the end of the sequence, we compare its length with the previous longest sequence found and update the result accordingly. The time complexity of this approach is $O(n \log n)$, and the space complexity is $O(1)$.
Optimized approach using union find
We will solve this problem with the help of the union find pattern and use the union by rank and path compression variation of the algorithm. The goal is to find the consecutive elements in the array, which can be done by connecting the elements to a single parent element. For this purpose, we create dictionaries to store the parent of each element and the size of each sequence. We will initialize the parent of each element to itself and the length of each sequence to be $1$ initially.
For each element $num$ in the input array, we’ll check if $num + 1$ is present in our parent dictionary. If it is present, we’ll apply a Union
method of the UnionFind
class on $num$ and $num + 1$.
Here are the steps that will be carried out in the Union
method:

Find the roots of sequences containing the given elements using the
Find
method. If they are not equal, combine the roots of these consecutive sequences by setting the parent of the root of the smaller sequence to the root of the larger sequence. 
Update the length of the larger sequence by adding the current sequence’s length and the smaller sequence’s length.

Update
maxLength
as below. This compares the current value ofmaxLength
with the updated length of the larger sequence (xRoot
) and stores the larger of the two values inmaxLength
.
maxLength = max(maxLength, size[xRoot])
We will carry out the steps above for each $num$ in the input array and then return the length of the longest consecutive sequence.
Level up your interview prep. Join Educative to access 80+ handson prep courses.