DSA Visualizer · 25 visualizationsLongest Consecutive Sequence
MediumArrays & Hashing

Longest Consecutive Sequence

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.

nums = [100, 4, 200, 1, 3, 2]Step 1 of 11
100
0
4
1
200
2
1
3
3
4
2
5
set
100
4
200
1
3
2

Put every value in a set so “is x in the array?” is O(1). Look for numbers that start a run — no x−1 in the set.

Pythontime O(n) · space O(n)
1def longestConsecutive(nums):
2 numSet = set(nums)
3 best = 0
4 for num in numSet:
5 if num - 1 not in numSet:
6 length = 1
7 while num + length in numSet:
8 length += 1
9 best = max(best, length)
10 return best
Variables
num—
isStart—
length—
best0

Problem

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

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

The longest run is [1,2,3,4]

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

Constraints

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

Intuition

Put every value in a hash set for O(1) membership checks. A value only needs to be examined as the *start* of a run — one whose predecessor (value − 1) isn't in the set. From each start, count forward while the next value is present. Every number gets counted inside at most one run across the whole pass, so the total work is still O(n) even though it looks like nested loops.

Brute force → Optimal

Brute force

Sort the array, then scan once counting the longest run of adjacent values that differ by 1.

Time O(n log n)Space O(1) extra (or O(n) if sorting isn't in place)
Optimal

Hash set of all values; only start counting from values with no predecessor in the set, then count forward.

Time O(n)Space O(n)

Complexity

Time O(n)Space O(n)

Edge cases

  • Empty array: the answer is 0 — there's no run to find.
  • Duplicate values, e.g. the two 0s in [0,3,7,2,5,8,4,6,0,1]: the set collapses them to one value, so they don't inflate the run length.

Common mistakes

  • Starting the forward count from every value instead of only values with no predecessor — that turns the algorithm back into O(n²) on a long run.
  • Sorting without first deduplicating, which can overcount a run when the same value repeats.
Two Sum is free. Enroll to unlock every visualization and save where you stopped.Enroll free