#128MediumHash Set

Longest Consecutive Sequence

Use a hash set to start counting only from sequence beginnings.

AmazonGoogleFacebookMicrosoftAirbnb

Problem Statement

Given an unsorted array of integers nums, return the length of the longest consecutive elements sequence. You must write an algorithm that runs in O(n) time.

Examples

Example 1

Input:nums = [100,4,200,1,3,2]
Output:4

Explanation: The longest consecutive sequence is [1,2,3,4], length 4.

Example 2

Input:nums = [0,3,7,2,5,8,4,6,0,1]
Output:9

Constraints

  • 0 ≤ nums.length ≤ 10⁵
  • -10⁹ ≤ nums[i] ≤ 10⁹

Solutions

1
Sort then scan
TimeO(n log n)SpaceO(1)

Sort the array. Iterate and track the current streak length. O(n log n) — violates the O(n) requirement.

Visual Animation
def longestConsecutive(nums: list[int]) -> int:
    if not nums: return 0
    nums = sorted(set(nums))
    best = cur = 1
    for i in range(1, len(nums)):
        if nums[i] == nums[i-1]+1: cur += 1
        else: cur = 1
        best = max(best, cur)
    return best

Related Concepts

Deepen your understanding with these related topics from our AI Glossary:

Deepen your understanding

Want to master the core concepts?

Our free AI Glossary covers 190+ topics — from Hash Set to Dynamic Programming, Machine Learning, SQL, and more. Structured learning tracks for every level.

Browse AI Glossary All Problems
39+
AI Models
₹69
Per day used
4
Languages

Stuck? Ask AI to explain it step by step.

Ask Claude, GPT-4o, or Gemini to debug your code, generate test cases, or walk through the intuition. 39+ models. Pay only on days you use it — no subscription required.

Free to start · No credit card required to explore

Get Started Free
Back to all problems