AlgoMaster Logo

Longest Consecutive Sequence

Ashish

Ashish Pratap Singh

medium

Problem Description

Solve it on LeetCode

Approaches

1. Sorting

Intuition:

The simplest way to find the longest consecutive sequence is to first sort the array. Once sorted, a consecutive sequence will appear as continuous numbers in the array. We can then iterate through the sorted array to count the lengths of consecutive sequences and return the length of the longest one.

  1. Sort the Array: Sorting the array costs O(n log n) time.
  2. Initialize counters: Use currentStreak to keep track of the streak length, and longestStreak to store the maximum length.
  3. Iterate through the Array:
    • Continue the streak if consecutive numbers are found.
    • Reset currentStreak if a gap is found.
  4. Return the longest streak.

Code:

Intuition:

We can leverage a HashSet to eliminate duplicates and achieve O(n) complexity for finding consecutive sequences by only attempting to build from numbers that are not part of any smaller sequence.

  1. Add numbers to HashSet: This allows constant-time lookups.
  2. Iterate over the Set:
    • For each number, check if it is the start of a sequence.
    • Calculate the length of that sequence by incrementing and checking the presence of subsequent numbers.
  3. Track the maximum sequence length.

Code:

3. Union-Find

Intuition:

We can use the union-find data structure to connect numbers that are part of consecutive sequences. Each element is a node, and paths connect consecutive numbers. Using path compression and union, we can efficiently find the size of the largest connected component, which corresponds to the longest sequence.

  1. Initialization: Treat each element in the array as its own set.
  2. Union by Rank: Connect consecutive numbers.
  3. Find the maximum component size.

Code: