Arrays & Hashing

Hash Set Sequence Starts

Longest Consecutive Sequence

1Question

Longest Consecutive Sequence

MediumLeetCode 128 ↗

You are given an array of numbers nums that is not sorted. Find the length of the longest run of consecutive numbers (like 1, 2, 3, 4) that you can build from its values.

Rules

The numbers in the run do not need to be next to each other in the array. Only the values matter. Your algorithm must run in O(n) time.

Examples
Example 1
Input: [100,4,200,1,3,2]
Output: 4

The run is 1, 2, 3, 4. It has length 4.

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

The run is 0, 1, 2, 3, 4, 5, 6, 7, 8. The extra 0 does not count twice.

Example 3
Input: [1,0,1,2]
Output: 3

The run is 0, 1, 2. The duplicate 1 is counted only once.

Constraints

0 ≤ nums.length ≤ 105

Up to 100,000 numbers. The array can also be empty, and then the answer is 0.

−109 ≤ nums[i] ≤ 109

Values can be negative and very large, so we use a hash set, not an array of flags.

Follow-up

You must write an algorithm that runs in O(n) time. Sorting alone costs O(n log n), so we need a smarter idea.

2Hints

Open one hint at a time. Try to think before you open the next one.

3Pattern

Pattern name

Hash Set Sequence Starts

Put everything in a set, then only walk a run from its first number.

A set answers “does this value exist?” in O(1). If we also know where each run begins, we can count every run exactly once, with no sorting:

start: (num − 1) not in set; length: count while (num + k) in set

Every run has exactly one start. Numbers in the middle of a run are skipped, so no number is walked over again and again.

How to spot this pattern

  • The question is about values that follow each other (1, 2, 3, ...) in an unsorted array.
  • The order in the array does not matter, only which values exist.
  • The problem asks for O(n), which rules out sorting.
  • You are allowed O(n) extra memory for a set.

4Explanation

The big idea: Put all numbers in a set called num_set. Then for each number num, ask one question first:

Is num − 1 in the set?

Yes: num is in the middle of a run. Skip it. Someone earlier will count this run.

No, it is not.

Then num is the start of a run. Count num + 1, num + 2, ... while they are in the set.

Why is it O(n) and not O(n²)? Each run is walked only from its start. A number inside a run is checked once (and skipped), and then walked over once by the start of its run. So every number is touched a small, fixed number of times.

What about duplicates? A set keeps each value only once, so a repeated number can never make a run longer.

5Brute Force

Sort the values, then count each run of +1 steps.

Idea

After sorting, numbers of the same run sit next to each other. So we:

  • Remove duplicates and sort the values.
  • Walk through the list. If the number is previous + 1, the run grows by 1.
  • Otherwise the run is broken, so start a new run with length 1.
  • Remember the longest run you saw.
Python
def longest_consecutive_brute(nums):
    if not nums:
        return 0

    values = sorted(set(nums))        # no duplicates, in order
    best = 1
    run = 1

    for i in range(1, len(values)):
        if values[i] == values[i - 1] + 1:
            run += 1                  # same run keeps growing
        else:
            run = 1                   # gap found, start a new run
        best = max(best, run)

    return best


print(longest_consecutive_brute([100, 4, 200, 1, 3, 2]))  # 4

6Optimal Solution

A hash set, counting only from the start of each run.

Python
def longest_consecutive(nums):
    num_set = set(nums)              # O(1) lookups, no duplicates
    best = 0

    for num in num_set:
        if num - 1 not in num_set:   # num is the START of a run
            length = 1
            while num + length in num_set:
                length += 1          # walk up the run
            best = max(best, length)

    return best


print(longest_consecutive([100, 4, 200, 1, 3, 2]))  # 4

7Time and Space Complexity

Let n be the number of items in the array.

Brute force (sort and scan)

Time: O(n log n)Space: O(n)

Optimal (hash set, walk from starts)

Time: O(n)Space: O(n)

How big is the difference?

Approximate number of steps:

nSort (n log n)Hash set (n)
10about 3310
1,000about 10,0001,000
100,000about 1.7 million100,000

For the biggest input in this problem, the hash set does around 17 times less work than sorting, and it is the only one that meets the O(n) rule.

8Visualization

Try:Use 1 to 15 whole numbers (from -99 to 99), separated by commas.
Current Element-
Current Length-
Best Length-
100
4
200
1
3
2

Step Analysis

Click "Next" to begin analysis.
Core Logic:
If num − 1 in set: skip (middle of a run)
Else (start): count num + 1, num + 2, ...
Then: best = max(best, length)