✅C++ || BEATS 95% || O(N) ||OPTIMIZED
PLEASE UPVOTE IF YOU FIND MY APPROACH HELPFUL, MEANS A LOT \uD83D\uDE0A\n\nExplanation:\n Insert all the elements of the array into set.\n Check if the previous
**PLEASE UPVOTE IF YOU FIND MY APPROACH HELPFUL, MEANS A LOT \uD83D\uDE0A**\n\n**Explanation:**\n* Insert all the elements of the array into set.\n* Check if the previous number (nums[i] - 1) is present in the set, if it is then that number (nums[i]) is not the starting of the sequence.\n* If previous number is not present, that means that number is the starting of the sequence.\n* Make a count variable to count the length of the sequence and current variable to store the current number.\n* Now in a while loop, traverse and keep searching for consecutive elements until the condition is false.\n* Now store the maximum of longest_sequence and current length of the sequence.\n\n**Time complexity: O(n)**\n**Space complexity: O(n)**\n\n```\nclass Solution {\npublic:\n    int longestConsecutive(vector<int>& nums) {\n        unordered_set<int> s(nums.begin(),nums.end()); // this is faster\n        \n        // for(int i = 0; i<nums.size(); i++)\n        // {\n        //     s.insert(nums[i]);\n        // }\n        \n        int longest_sequence = 0;\n        \n        for(int i=0; i<nums.size(); i++)\n        {\n            if(s.find(nums[i] - 1)!=s.end())\n                continue;\n            \n            else\n            {\n                int count = 0;\n                int current_element = nums[i];\n                \n                while(s.find(current_element) != s.end())\n                {\n                    count++;\n                    current_element++;\n                }\n                \n                longest_sequence = max(longest_sequence,count);\n            }\n        }\n        \n        return longest_sequence;\n    }\n};\n```
['C', 'C++']