Article start
DSA Course: Interview Patterns and Problem Solving
Module 9: Hashing & Prefix Sum

Longest Consecutive Sequence: Hash Set Pattern

Find the longest run of consecutive integers without sorting.

May 29, 2026·24

Learning Outcome

After this lesson, you should be able to use a hash set to detect sequence starts and avoid repeated expansion.

Problem Statement

Given an unsorted integer array, return the length of the longest consecutive sequence.

InputOutputWhy
nums = [100,4,200,1,3,2]4The longest consecutive run is 1,2,3,4.

Brute Force Approach

Sort the array and scan consecutive groups. This works, but sorting costs extra time.

Optimized Approach

Put every number in a set. Only start expanding from x when x

  • 1 is absent, because that means x is the beginning of a sequence.

Exact Pseudocode

seen = set(nums)
best = 0
for x in seen:
  if x - 1 is not in seen:
    length = 1
    while x + length is in seen:
      length += 1
    best = max(best, length)
return best

Reference Code

class Solution:
    def longestConsecutive(self, nums):
        seen = set(nums)
        best = 0

        for x in seen:
            if x - 1 not in seen:
                length = 1
                while x + length in seen:
                    length += 1
                best = max(best, length)

        return best

Sample Dry Run

StepStateResult
Build set{100,4,200,1,3,2}Lookups are O(1) average
x = 10 is absentStart sequence
Expand2,3,4 existlength = 4
Other numbers2,3,4 are skipped as startsanswer = 4

Complexity

MeasureValueReason
TimeO(n)Each number is inserted once and expanded only from true sequence starts.
SpaceO(n)The hash set stores unique numbers.

Edge Cases

  • Duplicates should not extend a sequence twice.
  • An empty array returns 0.
  • Negative numbers work the same as positive numbers.

Interview Checklist

  • Check x

    • 1 before expanding.
  • Iterate over the set, not necessarily the original array.
  • Do not sort if the target is linear time.

FAQs

Why only expand from sequence starts?

If x

  • 1 exists, then x belongs to a sequence that already starts earlier.

Why does this stay O(n)?

Every number is part of at most one successful expansion chain.

What is the core pattern?

Hash set lookup with sequence-start detection.

Test your knowledge

Take a quick quiz based on this chapter.

Discussion

0 comments

Sign in to share a question or add to the discussion.
Start the discussion

Ask a question or share what stood out to you.