LeetCode 128 Longest Consecutive Sequence - Implementation

The approach

Build a set for O(1)O(1) 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

O(n)O(n) time, O(n)O(n) space.