128. Longest Consecutive Sequence

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

Your algorithm should run in O(n) complexity.

Example:

Input: [100, 4, 200, 1, 3, 2]
Output: 4
Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4.
// Hashset
int longestConsecutive(vector<int>& nums) { // time: O(n); space: O(n)
    unordered_set<int> st(nums.begin(), nums.end());
    int res = 0;
    for (int num : nums) {
        if (!st.count(num)) continue;
        st.erase(num);
        int prev = num - 1, next = num + 1;
        while (st.count(prev)) {
            st.erase(prev--);
        }
        while (st.count(next)) {
            st.erase(next++);
        }
        res = max(res, next - prev - 1);
    }
    return res;
}

Last updated

Was this helpful?