๐Ÿ”ข Longest Consecutive Sequence

NikhithaNikhitha
2 min read

๐Ÿ“Œ Problem Statement

Given an unsorted array of integers nums, return the length of the longest consecutive elements sequence.

You must solve the algorithm in O(n) time complexity.


๐Ÿง  Intuition

The first instinct might be to sort the array and check consecutive numbers โ€” but sorting takes O(n log n), which is too slow for this problem.

So how can we find consecutive sequences in O(1) lookup time?

๐Ÿ‘‰ We use a hash set (unordered_set in C++) to:

  • Store all numbers for quick access

  • Check if a number starts a sequence (i.e., if num - 1 is not in the set)

This helps us ensure each number is processed only once, resulting in an overall O(n) solution.


๐Ÿงฉ Logic and Approach

  1. Insert all numbers into a hash set.

  2. Loop through each number in the set:

    • If num - 1 is not in the set, this is the start of a sequence.

    • From that number, keep checking for num + 1, num + 2, etc.

    • Count how many numbers are in that streak.

  3. Update a variable longestLength to keep track of the maximum streak found.

We avoid counting the same sequence multiple times by only starting when the current number has no predecessor (num - 1).


โœ… C++ Code (Clean & Simple)

class Solution {
public:
    int longestConsecutive(vector<int>& nums) {
        if (nums.empty())
            return 0;

        unordered_set<int> numberSet;
        for (int num : nums) {
            numberSet.insert(num);
        }

        int longestLength = 0;

        for (int num : numberSet) {
            // Only start counting if it's the beginning of a sequence
            if (numberSet.find(num - 1) == numberSet.end()) {
                int currentNum = num;
                int currentLength = 1;

                while (numberSet.find(currentNum + 1) != numberSet.end()) {
                    currentNum += 1;
                    currentLength += 1;
                }

                longestLength = max(longestLength, currentLength);
            }
        }

        return longestLength;
    }
};

๐Ÿ” Example

Input: nums = [100, 4, 200, 1, 3, 2]
Output: 4

Explanation:

  • The longest consecutive sequence is [1, 2, 3, 4]

  • Length = 4


๐Ÿงฎ Time & Space Complexity

ComplexityValue
TimeO(n)
SpaceO(n) (for set)

๐Ÿ“˜ Summary

This is a classic hash-based optimization problem where:

  • You avoid sorting

  • Use unordered_set to check for sequence continuity

  • Only start counting from the beginning of each possible sequence

Itโ€™s a perfect example of how to use hashing to speed up search-based logic.

problem link: https://leetcode.com/problems/longest-consecutive-sequence/description/

0
Subscribe to my newsletter

Read articles from Nikhitha directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Nikhitha
Nikhitha

๐Ÿš€ Software Developer | DSA Enthusiast | Problem Solver ๐Ÿ”น Sharing daily DSA solutions, coding insights, and interview prep ๐Ÿ”น Passionate about writing optimized & bug-free code