[VIDEO] Step-by-Step Visualization Using a Set
https://www.youtube.com/watch?v=gbMlwKENRj0\n\nOne way to solve this would be to first sort the array. Then we could easily traverse the array in order to find 
https://www.youtube.com/watch?v=gbMlwKENRj0\n\nOne way to solve this would be to first sort the array. Then we could easily traverse the array in order to find the length of the longest consecutive sequence.  The problem with this approach, though, is that the cost of sorting is O(n log n).  So in order to write an algorithm that runs in O(n) time, we need to figure out how to look up each element in the array in O(1) time.\n\nWe can do this by converting the array of integers into a set of integers.  Since sets use a hash function to generate a hash code for each value, we can look up each element in O(1) time (or more precisely, the amortized complexity of set lookup is O(1)).\n\nWe\'ll then traverse the array using `start` and do the following:\n1. If `start - 1` is in the set, then that means `start` is NOT the start of a consecutive sequnce, since we could have started at `start - 1` instead.  So we\'ll just move on to the next integer\n2. If `start - 1` is NOT in the set, then that means it IS the start of a consecutive sequence.  We\'ll initialize a variable `end` and set it equal to `start + 1` and see how long the sequence goes\n3. While `end` is in `num_set`, we\'ll continue to increment `end` to see how long the sequence can go.  Once `end` is no longer in `num_set`, the sequence has ended and we\'ll calculate the length.\n4. We\'ll do this by calculating `end - start`, and update `length` to be the length of the longest consecutive sequence that we\'ve encountered so far.\n\n# Code\n```\nclass Solution:\n    def longestConsecutive(self, nums: List[int]) -> int:\n        num_set = set(nums)\n        length = 0\n        for start in nums:\n            if start - 1 not in num_set:\n                end = start + 1\n                while end in num_set:\n                    end += 1\n                length = max(length, end - start)\n        return length\n```\n
['Array', 'Hash Table', 'Python', 'Python3']