Back to Practice
#0289

Longest Consecutive Sequence

MediumDSA28 min20 XP

Problem

Given nums, return the length of the longest consecutive sequence. The sequence values must increase by 1, but they do not need to be adjacent in the original list.

Why This Matters

This problem tests whether you can use a set to start work only at sequence beginnings instead of sorting.

Function Signature

def longest_consecutive(nums):

Examples

Example 1
Inputnums = [100,4,200,1,3,2]
Output4

The longest run is 1, 2, 3, 4.

Constraints

  • Return the exact requested value.
  • Handle edge cases cleanly.
  • Use the intended DSA pattern when brute force would scale poorly.
CodePython
Visible browser tests run here when available.
Testcases2 visible / 3 hidden categories
Classic unsorted run
Input[100,4,200,1,3,2]
Expected4

The values 1 through 4 form the longest sequence.

Duplicates included
Input[0,3,7,2,5,8,4,6,0,1]
Expected9

Duplicates do not break the 0 through 8 run.

Hidden Test Categories
empty inputnegative numbersall duplicates