Facebook PixelLongest Consecutive Sequence — Coding Practice
Longest Consecutive SequenceMedium

Longest Consecutive Sequence

Medium 20.1k47% acceptance
ArrayHash TableUnion Find

Given an unsorted integer array nums, return the length of the longest run of consecutive integers (values that differ by 1), regardless of their order in the array.

Your algorithm must run in O(n) time. Return 0 for an empty array.

Example 1
Input: nums = [100,4,200,1,3,2]
Output: 4
The consecutive run 1,2,3,4 has length 4.
Example 2
Input: nums = [0,3,7,2,5,8,4,6,0,1]
Output: 9
0 through 8 form a run of length 9; the duplicate 0 does not extend it.
Constraints
  • 0 ≤ nums.length ≤ 10⁵
  • -10⁹ ≤ nums[i] ≤ 10⁹
Asked atAmazonGoogleMetaMicrosoft
JavaScript
Loading editor…
Case 1
[100,4,200,1,3,2]
expected: 4
Case 2
[0,3,7,2,5,8,4,6,0,1]
expected: 9
Case 3
[]
expected: 0
Case 4
[1]
expected: 1
Case 5
[9,1,4,7,3,-1,0,5,8,-1,6]
expected: 7
Case 6
[1,2,0,1]
expected: 3