Complete-Preparation

🎉 One-stop destination for all your technical interview Preparation 🎉

View the Project on GitHub

128. Longest Consecutive Sequence 🌟🌟

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.

Sorting Solution

Hash table O(N) Time solution

Code

class Solution {
public:
    int longestConsecutive(vector<int>& nums) {
        int n = nums.size(), cnt=0, ans=0;
        if(n==0)return 0;
        unordered_set<int> st;
        for(auto x:nums)st.insert(x);
        for(auto x:nums){
            if(st.count(x-1)!=1){
                int currentNum = x;
                cnt=1;
                while(st.count(currentNum+1)){
                    currentNum++;
                    cnt++;
                }
                ans=max(ans,cnt);
            }
        }
        return ans;
    }
};