15% off all plans & roadmaps Use code

See plans

Longest Consecutive Sequence

Updated

TL;DR: Find the longest run of values that increase by 1 in an unsorted array, in O(n). Put every value in a hash set and only count forward from values whose predecessor is missing.

Problem

Given an integer array nums, return the length of the longest sequence of consecutive values. In a consecutive sequence each value is exactly 1 larger than the one before it. The values do not need to sit next to each other in nums.

Duplicates do not make a sequence longer, and the order of nums does not matter. Return 0 for an empty array. Your algorithm must run in O(n) time, where n is the length of nums.

Example 1

Input: nums = [14,9,11,10,13,15,15,2]
Output: 3
Explanation: The longest consecutive sequences are 9, 10, 11 and 13, 14, 15. Each has length 3. Value 12 is missing, so the two runs cannot join.

Example 2

Input: nums = [21,18,24,19,23,22,40,20]
Output: 7
Explanation: Every value from 18 through 24 is present, which gives a sequence of length 7.

Example 3

Input: nums = []
Output: 0
Explanation: An empty array has no values, so the answer is 0.

Constraints

  • 0 <= nums.length <= 10^5
  • -10^9 <= nums[i] <= 10^9
  • Every element of nums is an integer.
  • nums may contain duplicate values.

Constraints that matter

  • n up to 10^5 rules out any O(n^2) or O(n^3) scan. Those need around 10^10 or more steps in the worst case.
  • The O(n) requirement rules out sorting as the final answer, because comparison sorting costs O(n log n). Sorting still passes the real tests, but it does not meet the stated bound.
  • Values range from -10^9 to 10^9, so you cannot use a plain array indexed by value. You need a hash set or a sort.
  • Duplicates are allowed, so a repeated value must never lengthen a run. A set removes them for free.
  • n can be 0, so the answer must be 0 for an empty array and the code must not read nums[0] unguarded.

View on LeetCode

Hints

Hint 1

This is a hashing problem built on existence checks.

Hint 2

Treat every element as a possible start.

Solution

Intuition

This is a hashing problem built on existence checks. The question you keep asking is: is value x in the array? Answering that by scanning costs O(n). Answering it with a hash set costs O(1) on average, so once membership is cheap you can walk a run one step at a time without sorting.

Picture a hallway of numbered lockers, some open and some closed. The hash set is a quick roster of which lockers are open, and a run starts only at an open locker whose left neighbor is closed.

The second thing to notice is where a run starts. A value x begins a run exactly when x - 1 is absent. If x - 1 is present, then x sits inside a run that some smaller value already owns. So you only count forward from values with no predecessor.

This is why the total work is linear. Each run is walked once, from its smallest value, and every value belongs to exactly one run. The inner while loop therefore touches each distinct value at most once across the whole algorithm.

The outer loop touches each value once as well. That gives about 2 * (distinct values) set lookups for the walks, plus one predecessor check per value.

If you skip the predecessor check, the code is still correct but slow. On a fully consecutive array of 10^5 values, value 1 walks 10^5 steps, value 2 walks 99,999 steps, and so on. That is about 5 * 10^9 steps, which is the O(n^2) trap.

Watch the pattern animation

Worked example

Input: nums = [14, 9, 11, 10, 13, 15, 15, 2]
Output: 3
Explanation: The distinct values are 2, 9, 10, 11, 13, 14, 15. The run 9, 10, 11 has length 3 and the run 13, 14, 15 has length 3. The extra 15 is a duplicate and adds nothing. The value 12 is absent, so the runs stay separate and the answer is 3.

Approach 1: Brute force

Treat every element as a possible start. From it, ask whether value + 1 is in the array by scanning the whole array. If yes, ask about value + 2, and keep going until a value is missing. Track the longest run you reach.

This is the version a beginner writes first. It needs no extra memory and handles duplicates without special code, because a duplicate start repeats the same walk.

Steps

  1. Set best to 0.
  2. For each value v in nums, set length to 1.
  3. While v + length appears anywhere in nums (a full linear scan), increase length by 1.
  4. Set best to the larger of best and length.
  5. Return best after all starts are tried.

Dry run

Trace on [14, 9, 11, 10, 13, 15, 15, 2]. Each start walks forward with a scan per check.

  • Start 14: 15 found, 16 not found. Length 2.
  • Start 9: 10 and 11 found, 12 not found. Length 3. Best is 3.
  • Start 11: 12 not found. Length 1.
  • Start 10: 11 found, 12 not found. Length 2.
  • Start 13: 14 and 15 found, 16 not found. Length 3.
  • Start 15 (twice): 16 not found. Length 1 each.
  • Start 2: 3 not found. Length 1.

The largest length seen is 3, which is the answer.

Complexity

TimeO(n^3)
SpaceO(1)

Let n be the length of nums. There are n starts, and each walk can take up to n steps, for example on a fully consecutive array. Each step is a linear scan of n elements. That multiplies to n * n * n in the worst case, so time is O(n^3). Extra memory is a few integers, so space is O(1).

PythonTested in our runner

from typing import List, Optional

class Solution:
    def longestConsecutive(self, nums: List[int]) -> int:
        best = 0
        for v in nums:
            length = 1
            # each membership test scans the whole list
            while (v + length) in nums:
                length += 1
            best = max(best, length)
        return best

Approach 2: Sort, then count runs

What's slow: every membership test is a full scan, and the same values are searched again and again. The insight that fixes it is that sorting puts neighbours next to each other. After a sort, a run of consecutive values is a block of adjacent cells, so you can find it in one pass.

Walk the sorted array and compare each value to the one before it. If it equals the previous value, skip it, since it is a duplicate. If it is exactly 1 larger, extend the current run. Otherwise the run is broken and a new one starts at length 1.

Steps

  1. Return 0 if nums is empty.
  2. Copy nums and sort the copy in ascending order.
  3. Set best and current to 1.
  4. For each index i from 1, compare a[i] with a[i - 1].
  5. If they are equal, skip. If a[i] is a[i - 1] + 1, add 1 to current. Otherwise reset current to 1.
  6. After each step, set best to the larger of best and current.
  7. Return best.

Dry run

Sorted copy of the example: [2, 9, 10, 11, 13, 14, 15, 15].

ia[i]previousactioncurrentbest
02nonestart11
192gap, reset11
2109extend22
31110extend33
41311gap, reset13
51413extend23
61514extend33
71515duplicate, skip33

The answer is 3.

Complexity

TimeO(n log n)
SpaceO(n)

Let n be the length of nums. The sort costs O(n log n) comparisons, and the single pass afterward does n constant-time steps, so the sort dominates. The copy of the array uses O(n) space. If you may sort the input in place, the extra space drops to the sort's own stack, which is O(log n) in typical implementations.

PythonTested in our runner

from typing import List, Optional

class Solution:
    def longestConsecutive(self, nums: List[int]) -> int:
        if not nums:
            return 0
        a = sorted(nums)
        best = current = 1
        for i in range(1, len(a)):
            if a[i] == a[i - 1]:
                continue  # duplicate adds nothing
            if a[i] == a[i - 1] + 1:
                current += 1
            else:
                current = 1
            best = max(best, current)
        return best
Hashing - Previously Seen / Existence Check pattern infographic for Longest Consecutive Sequence

Solution pattern

Hashing - Previously Seen / Existence Check

Part of Array/Matrix Manipulation Patterns

Approach 3: Hash set with run startsOptimalHashing - Previously Seen / Existence Check

What's slow: sorting costs O(n log n), and the problem asks for O(n). The order of the whole array is more than you need. You only need to know whether a given value exists. The insight that fixes it is to store every value in a hash set and to count only from values that begin a run.

A value x begins a run when x - 1 is not in the set. For those values, walk x + 1, x + 2, and so on until one is missing. Values in the middle of a run are skipped, so no run is walked twice.

Why it is correct. Every value in the set sits in exactly one maximal run of consecutive integers. Each such run has one smallest value, and that value is the only one whose predecessor is absent. So the walk from that smallest value covers the whole run, and skipping the other values loses no run.

Steps

  1. Build a hash set from nums. Duplicates collapse here.
  2. Set best to 0.
  3. For each value x in the set, check whether x - 1 is in the set.
  4. If x - 1 is present, skip x. Some smaller value owns this run.
  5. Otherwise set length to 1 and increase it while x + length is in the set.
  6. Set best to the larger of best and length.
  7. Return best. An empty input leaves best at 0.

Dry run

Set built from the example: {2, 9, 10, 11, 13, 14, 15}. The table visits values in sorted order. Real set order is unspecified, and the result does not depend on it.

xx - 1 in set?actionwalklengthbest
2norun start3 absent11
9norun start10, 11 present, 12 absent33
10yes (9)skipnonenone3
11yes (10)skipnonenone3
13norun start14, 15 present, 16 absent33
14yes (13)skipnonenone3
15yes (14)skipnonenone3

The walks cover 2 in total from 9 and 2 from 13, plus the failed lookups. The answer is 3.

Complexity

TimeO(n)
SpaceO(n)

Let n be the length of nums. Building the set takes n insertions. The outer loop visits each distinct value once and does one predecessor lookup. The inner while loop runs only from run starts, and each run is walked once from its smallest value. So all inner steps together touch each distinct value at most once.

That gives about 3n lookups, which is O(n) expected time. The set holds up to n values, so space is O(n).

PythonTested in our runner

from typing import List, Optional

class Solution:
    def longestConsecutive(self, nums: List[int]) -> int:
        values = set(nums)
        best = 0
        for x in values:
            if x - 1 in values:
                continue  # not the start of a run
            length = 1
            while x + length in values:
                length += 1
            best = max(best, length)
        return best

Common mistakes

  • Walking forward from every value, so the predecessor check if x - 1 in values is missing. The answer stays right but a fully consecutive array costs O(n^2). Add the check and skip any value whose predecessor exists.
  • Iterating over nums instead of the set in the hash approach. Duplicates then repeat the same walk. A value like 5 repeated 10^5 times costs 10^5 walks of a short run. Loop over the set.
  • Reading a[0] in the sorting solution without handling an empty array. Return 0 first, then start best and current at 1.
  • Treating a duplicate as a break in the sorted scan. If you write else: current = 1 for a[i] == a[i - 1], the input [1, 2, 2, 3] returns 2. Skip equal neighbours with continue instead.
  • Using a[i] - a[i - 1] == 1 in Java or C#. With values near -10^9 and 10^9 the difference can overflow int. Compare a[i] == a[i - 1] + 1 instead, which stays in range.
  • Deleting values from the set while iterating over it to avoid rework. This is a runtime error in Python and undefined behaviour in C++. Use the predecessor check, or iterate over a copy of the values.

Edge cases

  • [] returns 0, since no values means no sequence.
  • [7] returns 1. A single value is a run of length 1.
  • [5, 5, 5] returns 1. Duplicates collapse to one distinct value.
  • [1, 2, 3, 4, 5] returns 5. One run covers the whole array, which tests the predecessor skip for speed.
  • [-1, 0, 1] returns 3. The run crosses zero and uses negatives.
  • [1000000000, -1000000000] returns 1. The extreme values are far apart, and x + length must not overflow an int.
  • [1, 3, 5, 7] returns 1. No two values are adjacent.

Follow-ups interviewers ask

Can you solve it without a hash set and without sorting, in O(1) extra space?
Not in O(n) time that I know of. The set is what gives O(1) lookups, and sorting needs either O(n log n) time or a copy. If you may reorder the input in place, sorting gives O(n log n) time and small extra space. The honest trade-off is time versus memory: O(n) time needs O(n) memory.
Your set solution says O(n). Is that a worst-case bound?
It is an expected bound. Each set operation is O(1) on average, but a bad hash function with many collisions can make a single lookup slower. In an interview you state that the bound assumes average-case hashing. If you need a worst-case guarantee, use a balanced tree set and pay O(n log n).
How would you handle a stream of numbers arriving one at a time, with queries for the current longest run?
Keep a hash map from each run endpoint to the run length. When a new value x arrives, read the lengths of the runs ending at x - 1 and starting at x + 1. Then write the merged length to the two new endpoints and update a running maximum. Each insert is O(1) on average. Union-find over values gives the same result with a different structure.

Longest Consecutive Sequence FAQ

What is the time complexity of Longest Consecutive Sequence?

The hash set solution runs in O(n) expected time and uses O(n) space. The sorting solution runs in O(n log n) time. The brute force solution that scans the array for every next value is O(n^3) in the worst case.

Why use a hash set for Longest Consecutive Sequence?

The whole problem reduces to asking whether a value exists. A hash set answers that in O(1) on average, where an array scan costs O(n). It also removes duplicates when you build it, so repeated values cannot inflate a run.

Why only start counting when x - 1 is missing?

A value with a predecessor lies inside a run that a smaller value already covers. Counting from it would repeat work. Starting only at run beginnings means each run is walked once, which keeps the total at O(n).

Can Longest Consecutive Sequence be solved in O(1) extra space?

Not with O(n) time. The hash set needs O(n) space. Sorting in place uses little extra space but costs O(n log n) time, which misses the stated requirement. So you trade time for space, and you cannot have both here.

Does the inner while loop make the hash set solution O(n^2)?

No. The while loop starts only at run starts, and each run is walked once. Every distinct value is visited by at most one walk. The loops together do work proportional to n, not n multiplied by the run length.

How does the solution handle duplicates in Longest Consecutive Sequence?

The set approach drops them when it builds the set. The sorting approach skips a value equal to its neighbour. In both cases the example [14, 9, 11, 10, 13, 15, 15, 2] counts 15 once and returns 3.

Asked at

See which companies ask this — Pro

Practise it