Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Find the longest consecutive sequence

Given an unsorted list of integers, find the length of the longest run of consecutive integers. Use hashing for O(n) time.

Python practice15 minHashing & SetsIntermediateLast updated March 26, 2026

Problem statement

You are given an unsorted list of integers nums. Return the length of the longest sequence of consecutive integers that can be formed from elements of nums. The sequence elements must be consecutive integers, but the order in the input does not matter. Aim for O(n) average time complexity using a hash-based approach.

Task

Practice using sets for O(1) membership checks to compute the longest consecutive sequence in an array.

Examples

Example 1

Input

longest_consecutive([100, 4, 200, 1, 3, 2])

Output

4

The longest consecutive sequence is [1, 2, 3, 4], so the length is 4.

Input format

A list of integers: nums

Output format

An integer representing the length of the longest consecutive sequence

Constraints

0 <= len(nums) <= 10^5; integers may be negative; aim for O(n) average time using a set

Samples

Sample 1

Input

[100, 4, 200, 1, 3, 2]

Output

4

Longest run is [1,2,3,4] -> length 4