c++ || Python || easy to understand || using hasmap
Though all solutions here are fundamentally the same, I am using a few tricks to make the code faster and cleaner.\n\n The hash-set S contains the numbers we ha
Though all solutions here are fundamentally the same, I am using a few tricks to make the code faster and cleaner.\n\n* The hash-set S contains the numbers we haven\'t visited yet.\n* The main loop continues until the set is no longer large enough to make a difference.\n* We immediately start walking in both directions when we find any number.\n* We erase all visited numbers from the set as we go.\n* We use some nice C++ idioms, like the range constructor and the erase method that returns a value.\n\n**Time Complexity :**` O(N)`\n**Space Complexity :** `O(N)`\n\n**\u2714\uFE0F C++ Solution**\n\n```\nclass Solution {\npublic:\n    int longestConsecutive(vector<int>& nums) {\n        unordered_set<int> record(nums.begin(), nums.end());\n        int ans=0;\n        for(int it: nums){\n            if(record.find(it)==record.end())   continue;\n            int prev = it-1, next = it+1;\n            while(record.find(prev)!=record.end()) prev--;               // walk left on the number line, erasing numbers as you go,\n            while(record.find(next)!=record.end()) next++;              // walk right on the number line, erasing numbers as you go,\n            ans = max(ans, next-prev-1);                    // and consider the length of the resulting sequence.\n            record.erase(it);    //must do other wise you got tle\n        }\n        return ans;\n\t\t//upvote if you like\n    }\n};\n```\n\n**\u2714\uFE0F Python Solution**\n```\nclass Solution:\n    def longestConsecutive(self, nums: List[int]) -> int:\n        max_len = 0\n        num_set = set(nums)\n        for num in nums:\n            if num - 1 not in num_set:\n                curr_num = num\n                curr_len = 1\n                while curr_num + 1 in num_set:\n                    curr_num += 1\n                    curr_len += 1\n                max_len = max(max_len, curr_len)\n        return max_len\n```
['Hash Table', 'C']