Build a set for lookups. Only count from sequence starts where num - 1 is absent.
Here's the solution:
function longestConsecutive(nums): numSet = set(nums) longest = 0 for num in numSet: if num - 1 not in numSet: length = 1 while num + length in numSet: length += 1 longest = max(longest, length) return longest
time, space.