Skip to main content

Longest Run of Consecutive Numbers

MediumArraysHash map303 tests

You are given an unsorted integer array nums.

Find the largest group of values from nums that form a run of consecutive integers, such as 4, 5, 6, 7. The values can be anywhere in the array, in any order.

Return the length of the longest run. If nums is empty, return 0.

Note

A value that appears more than once is counted only once in a run.

Sorting gives an O(n log n) answer. Try for O(n): put all values in a set. A run starts at a value x only when x - 1 is not in the set. From each start, count upward.

Examples

Example 1

Input:
[10,-1,0,11,1,-2,12]
Output:
4

The values -2, -1, 0, 1 form a run of length 4. The values 10, 11, 12 form a shorter run of length 3.

Example 2

Input:
[]
Output:
0

There are no values, so the answer is 0.

Example 3

Input:
[3,2,3,1,2]
Output:
3

The distinct values are 1, 2, 3, which form a run of length 3. The repeated 2 and 3 do not make it longer.

Constraints

  • 0 <= nums.length <= 30
  • -50 <= nums[i] <= 50

Run checks your code against the 3 examples. Submit checks it against all 303 tests and needs a free account. You can also try ideas in the free JavaScript or Python compiler.