Skip to content

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.

InputOutputLongest sequence
[100,4,200,1,3,2]4[1,2,3,4]
[0,3,7,2,5,8,4,6,0,1]9[0,1,2,3,4,5,6,7,8]
  • 0 <= nums.length <= 10^5
  • -10^9 <= nums[i] <= 10^9
ApproachTimeSpaceBest When
Hash SetO(n)O(n)Required by problem, optimal
Sort FirstO(n log n)O(1)*Sorting allowed, simpler to implement
★ Recommended
⏱ Time O(n) Each number visited at most twice 💾 Space O(n) Set stores all numbers

Put all numbers in a hash set. For each number n, only start counting if n-1 is not in the set — that means n is the beginning of a sequence. Then count n, n+1, n+2, ... as long as they’re in the set. Track the maximum streak found.

Despite the nested loop appearance this is O(n) total because each number is visited at most twice: once as a candidate start, and at most once as part of a sequence expansion.

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

Set = {100, 4, 200, 1, 3, 2}

numn-1 in set?ActionStreakMax
10099 ✗count: 100 → streak 111
43 ✓skip (not start)1
200199 ✗count: 200 → streak 111
10 ✗count: 1,2,3,4 → streak 444
32 ✓skip4
21 ✓skip4

Animated walkthrough

Hash set: finding the longest consecutive sequence

Use Next or Autoplay to see how we build the set, identify sequence starts, and expand each sequence rightward.

Step 1 of 6
Waiting to begin...
Array state
Memory / lookup state

function longestConsecutive(nums):
num_set = set(nums)
best = 0
for n in num_set:
if (n - 1) not in num_set: # start of sequence
length = 1
while (n + length) in num_set:
length += 1
best = max(best, length)
return best
longest_consecutive_hash_set.py
from typing import List
def longest_consecutive(nums: List[int]) -> int:
num_set = set(nums)
best = 0
for n in num_set:
if (n - 1) not in num_set: # start of a sequence
length = 1
while (n + length) in num_set:
length += 1
best = max(best, length)
return best
✓ Simple
⏱ Time O(n log n) Sort-dominated 💾 Space O(1) In-place sort

Sort the array. Iterate through it, skipping duplicates. Reset the streak when a gap greater than 1 appears. Simple to implement but does not meet the O(n) requirement.

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

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

inums[i]nums[i-1]ActionStreakMax
121consecutive22
232consecutive33
343consecutive44
41004gap → reset14
5200100gap → reset14
function longestConsecutive(nums):
if not nums: return 0
nums.sort()
best = 1; streak = 1
for i in 1..len(nums)-1:
if nums[i] == nums[i-1]: continue # skip duplicate
if nums[i] == nums[i-1] + 1:
streak += 1
best = max(best, streak)
else:
streak = 1
return best
longest_consecutive_sort.py
from typing import List
def longest_consecutive(nums: List[int]) -> int:
if not nums:
return 0
nums.sort()
best = 1
streak = 1
for i in range(1, len(nums)):
if nums[i] == nums[i - 1]:
continue # skip duplicate
if nums[i] == nums[i - 1] + 1:
streak += 1
best = max(best, streak)
else:
streak = 1
return best
✓ Simple

A third approach demonstrating an alternative technique for solving this problem. This implementation optimizes either time or space complexity compared to the previous approaches.

⏱ Time O(n) Optimized complexity 💾 Space O(1) Efficient space usage
function approach3():
// Implementation approach goes here
longest_consecutive_sequence_space_optimized.py
"""
Solution for Longest Consecutive Sequence
"""
def solve():
"""Implementation for approach 3 of Longest Consecutive Sequence"""
pass
if __name__ == "__main__":
print("Solution ready")