Skip to content
DeepForgeby svx
All problems
HardData Structuresds-082

Longest Consecutive Sequence

Problem

Return the length of the longest run of consecutive integers in the list.

Put all values in a set, then only start counting from a value x when x - 1 is absent; extend upward while consecutive values exist. Every value is visited at most twice, so the algorithm runs in linear time.

Return 0 for an empty list.

Hint

Only begin a run when the previous integer is missing to avoid rescanning runs.

Test cases

case 1
in: [[100,4,200,1,3,2]]
expected: 4
case 2
in: [[]]
expected: 0
case 3
in: [[1,2,0,1]]
expected: 3
case 4
in: [[5]]
expected: 1
case 5
in: [[10,5,12,3,55]]
expected: 1
Starter codePython
def longest_consecutive(nums):
    # Your code here
    pass

5 test cases · run your code against them in the editor