Menu
CoddyTech

Longest Consecutive Sequence

MediumHashingpython iconjava iconcpp iconc iconjs icon+10

You get an array of integers nums in no particular order. A consecutive sequence is a group of values x, x+1, x+2 and so on, each of which appears somewhere in nums. Return the length of the longest consecutive sequence. A value that appears more than once counts once.

Function

longestConsecutive(nums: integer-array) → integer
numsinteger-array
the integers, in any order, repeats allowed
Returnsinteger
the length of the longest run of consecutive values present in nums

Constraints

  • 1 ≤ nums.length ≤ 104
  • -109 ≤ nums[i] ≤ 109
  • Values may repeat. Positions in the array do not matter, only which values are present.

Examples

Input
nums = [40, 4, 39, 1, 3, 2, 41]
Output
4
Explanation
1, 2, 3 and 4 are all present, a run of 4, even though they are scattered through the array. The other run, 39 to 41, has only 3 values.

lock icon+17 hidden tests on Submit

challenge icon

Follow-up

Suppose the values arrive one at a time, and after each one you must report the longest run so far. Can you keep the answer up to date in O(1) average time per value?

Reset code
def longestConsecutive(nums):
    # Write code here
Test cases

Case 1

Case 2

Case 3

Input

nums = [40, 4, 39, 1, 3, 2, 41]

Expected

4