Question
Given an unsorted array of integersÂ
nums
, return _the length of the longest consecutive elements sequence.You must write an algorithm that runs inÂ
O(n)
 time.
This is anarrays question.
Idea
- We want to turn the list into a set for O(1) indexing
- We iterate for every num in nums
- Try to find the start of a sequence (does num - 1 exist in the set)
- If you do find a start, keep count of the longest streak until the sequence runs out (does curr_num + 1 exist?)
- Update the current number
- Update the max sequence
- Try to find the start of a sequence (does num - 1 exist in the set)