C++ Easy Solution || Using Hash Table || Optimised Approach
Intuition\n Describe your first thoughts on how to solve this problem. \n* The intuition behind this code is to use a set to store all of the elements in the ar
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n* The intuition behind this code is to use a set to store all of the elements in the array. This allows us to quickly check if an element is the start of a new consecutive subsequence. We then iterate over the set, and for each element, we check if its predecessor is in the set. If it is not, then the element is the start of a new consecutive subsequence. We increment a counter for each consecutive subsequence that is found. The longest consecutive subsequence is the one with the largest counter.\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1) Create a set to store all of the elements in the array.\n2) Iterate over the set, and for each element, check if its predecessor is in the set. If it is not, then the element is the start of a new consecutive subsequence.\n3) The longest consecutive subsequence is the one with the largest counter.\n# Complexity\n- Time complexity: $$O(N)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(N)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n    int longestConsecutive(vector<int>& nums) {\n        int n = nums.size();\n        if(n == 0){\n            return 0;\n        }\n        int longest = 1;\n        unordered_set<int> st;\n        for(auto x : nums){\n            st.insert(x);\n        }\n        for(auto s : st){\n            if(st.find(s-1) == st.end()){\n                int count = 1;\n                int x = s;\n                while(st.find(x+1) != st.end()){\n                    count++;\n                    x = x+1;\n                }\n                longest = max(longest, count);\n            }\n        }\n        return longest;\n    }\n};\n```\n![UpvoteLeetcode.jpeg](https://assets.leetcode.com/users/images/a60f87a6-fd44-4617-a5a2-2b25878ee138_1684770197.189536.jpeg)\n
['Array', 'Hash Table', 'C++']