Longest Consecutive Sequence

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.

Example 1
Inputnums = [100,4,200,1,3,2]
Output4
The longest consecutive elements sequence is [1, 2, 3, 4], so its length is 4.
Example 2
Inputnums = [0,3,7,2,5,8,4,6,0,1]
Output9
The longest consecutive elements sequence is [0, 1, 2, 3, 4, 5, 6, 7, 8], so its length is 9.

Constraints

  • 0 <= nums.length <= 10^5
  • -10^9 <= nums[i] <= 10^9

Asked at 40 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate