Back to DSA sheet

Longest Consecutive Sequence

MediumArrays

Given an unsorted array, return the length of the longest run of consecutive integers (values differing by 1). The algorithm must run in O(n).

Input format (stdin): the first line has n. The second line has n integers (may be empty when n is 0). Output the longest run length.

Examples
Input: 6 100 4 200 1 3 2
Output: 4
1,2,3,4 form the longest run.
Input: 10 0 3 7 2 5 8 4 6 0 1
Output: 9
0..8 is a run of length 9.
Constraints
  • 0 <= n <= 10^5
  • -10^9 <= nums[i] <= 10^9
Sheets
Blind 75NeetCode 150NeetCode 250
longest-consecutive-sequence.cpp3 sample tests
Loading editor
Test results

Run the sample tests to check your solution against expected output.

Custom input (stdin)
Output

Run your code to see its output.