TC: O(N) Super Simple & Intuitive🚀✅
Approach\nThe code starts by initializing variables: n as the size of the input vector nums, an unordered set s initialized with the elements of nums, and ans a
# Approach\nThe code starts by initializing variables: n as the size of the input vector nums, an unordered set s initialized with the elements of nums, and ans as the variable to store the longest consecutive sequence length.\n\nNext, the code iterates through each element nums[i] in nums. For each element, it checks if nums[i]-1 (the previous number in a potential sequence) is present in the unordered set s. If nums[i]-1 is not found in s, it means that nums[i] is the lowest value of a potential consecutive sequence.\n\nThen, a counting loop starts, where it increments a count variable for each subsequent number in the sequence (num++) until the next number (num) is not found in the unordered set s. This loop calculates the length of the consecutive sequence starting from nums[i].\n\nFinally, the code updates the ans variable to be the maximum between the current ans and the count, which represents the length of the consecutive sequence starting from nums[i]. This ensures that the ans variable always stores the maximum length of a consecutive sequence encountered so far.\n\nAfter iterating through all elements of nums, the code returns the value stored in ans, which represents the length of the longest consecutive sequence in nums.\n\n# Complexity\n1. Time complexity: The time complexity of this code is O(n), where n is the size of the input vector nums. This is because the code iterates through the nums vector once and performs constant time operations (such as unordered set lookups and arithmetic operations) within the loop. The unordered set operations have an average time complexity of O(1).\n\n2.  Space complexity: The space complexity of this code is O(n), where n is the size of the input vector nums. This is because the code creates an unordered set s to store the unique elements of nums, which can potentially have a size of n in the worst case.\n\n# Code\n```\nclass Solution {\npublic:\n    int longestConsecutive(vector<int>& nums) {\n        int n=nums.size();\n        unordered_set<int> s(nums.begin(),nums.end());\n        int ans=0;\n        for(int i=0;i<n;i++){\n            // nums[i]-1 must not be in set, \n            // basically we will start from lowest value of any sequence, if nums[i]-1 exist then that nums[i] is not the lowest\n            if(s.find(nums[i]-1)==s.end()){// lowest one\n                int count=1; // nums[i] will be part of that sequence\n                int num=nums[i]+1; //next in sequence\n                while(s.find(num)!=s.end()){\n                    //counting all sequeces from nums[i]\n                    count++;num++;\n                }\n                ans=max(ans,count);\n            }\n            \n        }\n        return ans;\n    }\n};\n```
['C++']