Best O(N) Solution
Approach 1\nSorting\n\n# Complexity\n- Time complexity:\nO(nlogn) \n\n- Space complexity:\nO(1) \n\n# Code\n\nclass Solution {\npublic:\n    int longestConsecut
# Approach 1\nSorting\n\n# Complexity\n- Time complexity:\n$$O(nlogn)$$ \n\n- Space complexity:\n$$O(1)$$ \n\n# Code\n```\nclass Solution {\npublic:\n    int longestConsecutive(vector<int>& nums) {\n        if (nums.size() == 0)\n            return 0;\n        sort (nums.begin(), nums.end());\n        int ans = 1, count = 1;\n        for (int i = 1; i < nums.size(); i++) {\n            if (nums[i] == nums[i - 1] + 1) {\n                count++;\n                ans = max (ans, count);\n            } else if (nums[i] == nums[i - 1]) {\n                continue;\n            } else {\n                count = 1; \n            }\n        }\n        return ans;\n    }\n    }\n};\n```\n\n# Approach 2\nUsing HashSet\n\n# Complexity\n- Time complexity:\n$$O(n)$$ \n\n- Space complexity:\n$$O(n)$$ \n\n# Code\n```\nclass Solution {\npublic:\n    int longestConsecutive(vector<int>& nums) {\n        unordered_set <int> st;\n        for (int i = 0; i < nums.size(); i++)\n            st.insert(nums[i]);\n        int curr = 1, ans = 0;    \n        for (int i = 0; i < nums.size(); i++) {\n            if (st.find(nums[i] - 1) == st.end()) {\n                curr = 1;\n                while (st.find(nums[i] + curr) != st.end())\n                    curr++;\n                ans = max (curr, ans);    \n            }\n        }\n        return ans;\n    }\n};\n```
['C++']