The Indian Engineer

Problem 128 Longest Consecutive Sequence

Posted on Last edited 2 mins

Hashmap Count Set Hashset

Problem Statement

Link - Problem 128

Question

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

You must write an algorithm that runs in O(n) time.

Example 1

Input: nums = [100,4,200,1,3,2]
Output: 4
Explanation: The longest consecutive elements sequence is [1, 2, 3, 4].
Therefore its length is 4.

Example 2

Input: nums = [0,3,7,2,5,8,4,6,0,1]
Output: 9

Constraints

Solution

class Solution {
public:
    int longestConsecutive(vector<int>& nums) {
        std::ios::sync_with_stdio(false);
        unordered_set<int>s(nums.begin(),nums.end());
        int ans = 0,len =1;
        for(int num:nums){
            if(s.find(num-1)==s.end()){
                len = 1;
                while(s.find(num+len)!=s.end()){
                    len++;
                }
                ans = max(ans,len);
            }
        }
        return ans;
    }
};

Complexity Analysis

Algorithm Time Complexity Space Complexity
Hash set O(N) O(N)

Explanation

1. Intuition

2. Implementation

This solution was found by a random youtube short by neetcode. So huge shoutout to him !