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, xx and yy, are called consecutive if the difference between them is equal to 11.

Constraints:

  • 00 \leq nums.lengths 103\leq 10^{3}
  • 106-10^{6} \leq nums[i] 106\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(nlogn)O(n \log n), and the space complexity is O(1)O(1).

Optimized approach using union find

Level up your interview prep. Join Educative to access 80+ hands-on prep courses.