LeetCode #128 Medium

Longest Consecutive Sequence

Longest Consecutive Sequence is LeetCode 128 (Medium). You are given an unsorted integer array nums and must return the length of the longest run of consecutive integers whose values all appear in the array. GFG lists the same task as Longest Consecutive Subsequence.

  • The values can come from anywhere in the array; their positions do not matter, only whether each value is present.
  • Repeated values count once. A run never uses the same value twice.
  • An empty array has answer 0.

The array holds up to 10⁵ numbers, each between −10⁹ and 10⁹. The problem asks for an O(n) algorithm, which rules out sorting, and the value range rules out a counting array indexed by value.

Constraints
  • 0 <= nums.length <= 10⁵
  • -10⁹ <= nums[i] <= 10⁹
arrayhash-setunion-find
Open on LeetCode ↗
02

Intuition

Picture the values on a number line. They form separate blocks of consecutive integers, and the answer is the size of the biggest block.

A hash set answers "is v present?" in O(1), so you can walk a block from one end: from n, ask for n + 1, n + 2, and so on until one is missing. Walking from every value, though, re-walks each block many times: a block of length k is walked from all k of its values.

The fix is to walk only from the left end of each block, the values n whose n − 1 is missing. Every block has exactly one left end, so each block is walked once.

How to spot this pattern

When a problem is about runs of consecutive values (not consecutive positions) in an unsorted array and wants better than sorting, put the values in a hash set and only start a walk where the previous value is missing. The same trick counts runs of consecutive days, IDs or seat numbers.

03

Approach

Try it first

Before reading on, explain why the while loop inside the for loop does not make this O(n²). Count how many times each value can be stepped over by that inner loop.

1

Build the set

seen = set(nums). Repeats collapse into one entry, which is right because a repeated value never makes a run longer, and every membership test becomes O(1) on average.

2

Find the starts

For each value n in the set, check n - 1. If it is present, n is inside a run that starts further left: skip it. If it is absent, n starts a run.

3

Walk each run once

From a start, set length = 1 and increase it while n + length is in the set. When the next value is missing, the run is over; update best = max(best, length).

4

Why it is correct

Every maximal run of consecutive values has exactly one smallest value, and that value is the only one with no predecessor in the set. So every run is measured in full exactly once, and the largest measurement is the answer.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def longestConsecutive(self, nums: List[int]) -> int:
▶3 seen = set(nums)
▶4 best = 0
▶5 for n in seen:
▶6 if n - 1 in seen:
▶7 continue
▶8 length = 1
▶9 while n + length in seen:
▶10 length += 1
▶11 best = max(best, length)
▶12 return best
nums1004200132set1004200132runemptybest0set built: 6 distinct values
seen6 valuesno repeats
best0
Idea. Sorting would line the values up, but costs O(n log n). A hash set gives the same information one question at a time: is v + 1 present? Repeats collapse into one entry, which is right: a repeated value never lengthens a run.
nums1004200132set1004200132run99absent100length 1best099 is missing → 100 starts a run
n100
n − 199absent
length1
99 is not in the set, so nothing comes before 100: it is the left end of a run. Only from a start is it worth counting forward.
nums1004200132set1004200132run100101absentlength 1best1101 is missing → new best 1
n + length101absent
length1
best1
101 is missing, so the run from 100 ends with length 1. That beats the previous best of 0, so best = 1.
nums1004200132set1004200132run3in set4best13 is in the set → skip 4
n4
n − 13in the set
3 is in the set, so 4 sits in the middle of some run, not at its left end. Counting from here would only re-walk part of a run the real start will count in full, so skip it. This one check is what keeps the whole thing O(n).
nums1004200132set1004200132run199absent200length 1best1199 is missing → 200 starts a run
n200
n − 1199absent
length1
199 is not in the set, so nothing comes before 200: it is the left end of a run. Only from a start is it worth counting forward.
nums1004200132set1004200132run200201absentlength 1best1201 is missing → best stays 1
n + length201absent
length1
best1
201 is missing, so the run from 200 ends with length 1. The best stays 1.
nums1004200132set1004200132run0absent1length 1best10 is missing → 1 starts a run
n1
n − 10absent
length1
0 is not in the set, so nothing comes before 1: it is the left end of a run. Only from a start is it worth counting forward.
nums1004200132set1004200132run12length 2best12 is in the set → length 2
n + length2in the set
length2
2 is in the set, so the run 1…2 has length 2. Each value is reached this way at most once overall, because only its own run's start ever walks over it.
nums1004200132set1004200132run123length 3best13 is in the set → length 3
n + length3in the set
length3
3 is in the set, so the run 1…3 has length 3.
nums1004200132set1004200132run1234length 4best14 is in the set → length 4
n + length4in the set
length4
4 is in the set, so the run 1…4 has length 4.
nums1004200132set1004200132run12345absentlength 4best45 is missing → new best 4
n + length5absent
length4
best4
5 is missing, so the run from 1 ends with length 4. That beats the previous best of 1, so best = 4.
nums1004200132set1004200132run2in set3best42 is in the set → skip 3
n3
n − 12in the set
2 is in the set, so 3 sits in the middle of some run, not at its left end. Skip it.
nums1004200132set1004200132run1in set2best41 is in the set → skip 2
n2
n − 11in the set
1 is in the set, so 2 sits in the middle of some run, not at its left end. Skip it.
nums1004200132set1004200132runemptybest4every run counted → return 4
result4
Done. Every run was counted exactly once, from its own start, so the longest consecutive sequence has length 4. Every value was looked up a constant number of times: once as n, once as n − 1 from its right neighbour, once while being walked.
05

Sort, then scan

After sorting, consecutive values sit side by side. cur counts the run ending at index i: it grows when nums[i] is one more than the value before, stays put on a repeat, and restarts at 1 on a gap.

▶1class Solution:
▶2 def longestConsecutive(self, nums: List[int]) -> int:
▶3 if not nums:
▶4 return 0
▶5 nums = sorted(nums)
▶6 best = cur = 1
▶7 for i in range(1, len(nums)):
▶8 if nums[i] == nums[i - 1]:
▶9 continue
▶10 if nums[i] == nums[i - 1] + 1:
▶11 cur += 1
▶12 else:
▶13 cur = 1
▶14 best = max(best, cur)
▶15 return best
06

Common pitfalls

Walking forward from every value

✗ Wrong
for n in seen:
    length = 1
    while n + length in seen:
        length += 1
✓ Right
for n in seen:
    if n - 1 in seen:
        continue
    length = 1
    while n + length in seen:
        length += 1

Without the start check, a run of length k is walked from all k of its values, k(k+1)/2 steps. On range(10⁵) that is about 5 · 10⁹ lookups and a time-out.

Looping over nums instead of the set

✗ Wrong
for n in nums:
    if n - 1 in seen:
        continue
✓ Right
for n in seen:
    if n - 1 in seen:
        continue

If a run's start appears many times in nums, every copy passes the start check and walks the whole run again. An input of 50,000 copies of 0 followed by 1 to 50,000 makes about 2.5 · 10⁹ steps. The set holds each value once.

Counting repeats in a sorted scan

✗ Wrong
if nums[i] == nums[i - 1] + 1:
    cur += 1
else:
    cur = 1
✓ Right
if nums[i] == nums[i - 1]:
    continue
if nums[i] == nums[i - 1] + 1:
    cur += 1
else:
    cur = 1

In the sorting approach, [1, 2, 2, 3] must give 3. Treating the second 2 as a break resets the run; equal neighbours have to be skipped, not counted and not treated as a gap.

07

Edge cases

Empty array

The set is empty, the loop never runs, and best stays 0.

08

Complexity

Time
O(n)
Space
O(n)
Building the set is O(n). The outer loop does one lookup for n - 1 per distinct value. The inner while runs only from run starts, and each start walks its own run, so across the whole loop it steps over each value once, not once per start. That is at most about 3n average-O(1) lookups. The set holds up to n values.
09

Longest Consecutive Sequence FAQ

Does the order of iterating over the set matter?

No. Whatever order the set yields values in, a non-start is skipped in O(1) and each start walks its whole run. The total work and the answer are the same.

Can a hash set make this slow in the worst case?

Lookups are O(1) on average. Adversarial inputs that collide in the hash table can degrade them, which is why the bound is stated as average O(n). In practice, with Python's integer hashing or Java's HashSet, it runs in linear time.