Skip to main content
08

Longest Consecutive Sequence

Mediumhash set

Your code isn't saved yet: refreshing or leaving the page resets it. Saved progress comes with user accounts.

This problem uses:Arrays & HashingRead the beginner guide

Given an unsorted array of integers nums, return the length of the longest run of consecutive values that can be formed from its elements.

Your algorithm must run in O(n) time.

Understand the problem

  • Consecutive values are whole numbers that follow each other with no gaps: 1, 2, 3, 4 is a run of length 4. 1, 2, 4 is not one run, because 3 is missing.
  • The values don't need to be next to each other in the array, and the array isn't sorted. You're allowed to pick values from anywhere.
  • A duplicate value counts only once: [1, 2, 2, 3] has a run of length 3 (1, 2, 3), not 4.
  • O(n) means you can't sort the array first, because sorting takes O(n log n).

Example 1

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

The values 1, 2, 3, 4 are all in the array (scattered around), forming a run of 4. 100 and 200 are runs of length 1.

Example 2

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

Every value from 0 to 8 is present, a run of 9. The second 0 doesn't add anything.

Example 3

text
Input:  nums = []
Output: 0

Constraints

  • 0 <= nums.length <= 10^5
  • -10^9 <= nums[i] <= 10^9

Hints

Stuck? Open one hint at a time. Each one gives away a little more than the last.

    The idea in one sentence

    Put all values in a set, find the values that start a run (their left neighbour is missing), and count upward from each start.

    The naive approach (and why it's slow)

    • Sort, then scan: after sorting, a run is just neighbours that differ by 1. Simple and correct, but sorting is O(n log n), and the problem demands O(n).
    • Count from every value: for each x, check x + 1, x + 2, ... by scanning the array. Each check is a full scan, so this gets close to O(n³) in the worst case.

    The key insight

    Two ideas, one on top of the other:

    1. Make lookups instant. Put every value in a hash set, so "is x + 1 here?" takes one step.
    2. Only count each run once. Counting from every value repeats work: the run 1, 2, 3, 4 would be walked from 1, then from 2, then from 3... Instead, only start counting at the first value of a run. How do we know x is first? Because x - 1 is not in the set.
    Loading diagram...

    Step by step

    nums = [100, 4, 200, 1, 3, 2] → set = {100, 4, 200, 1, 3, 2}

    Valuevalue - 1 in set?Start of a run?Walk upwardLengthLongest so far
    10099: noYes100 (no 101)11
    43: yesNo, skip1
    200199: noYes200 (no 201)11
    10: noYes1, 2, 3, 4 (no 5)44
    32: yesNo, skip4
    21: yesNo, skip4

    Answer: 4.

    The code

    The reference solution is below, with comments on every important line.

    How fast is it?

    • Time: O(n). This surprises people, because there's a loop (while) inside a loop (for). But the inner walk only runs from starts, and each value belongs to exactly one run. So across the whole algorithm, each value is walked over at most once. Total work: about 2n steps, which is O(n).
    • Memory: O(n) for the set.

    Common mistakes

    • Skipping the "is it a start?" check. The code still gives the right answer, but a long run gets walked again from every one of its values, which is O(n²).
    • Looping over the array instead of the set. With many copies of a start value (like [1, 1, 1, ..., 2, 3]), you'd repeat the same walk once per copy. Looping over the set visits each distinct value once.
    • Forgetting the empty array. With no values, the answer is 0, and your loop should simply never run.

    Going deeper

    The "only act at the start of a group" trick is useful far beyond this problem: whenever nested loops make a solution look O(n²), ask whether each item is really processed more than once in total. If not, it's O(n). This kind of reasoning is called amortized analysis.

    Reference solution

    js
    /**
     * @param {number[]} nums
     * @return {number}
     */
    export default function longestConsecutive(nums) {
      // A set makes "is x here?" one step, and drops duplicates for free.
      const values = new Set(nums)
      let longest = 0
      // Loop over the SET, not the array, so each distinct value is visited once.
      for (const value of values) {
        // value - 1 exists, so value is in the middle of a run. Its run gets counted from its start.
        if (values.has(value - 1)) continue
        // value is the start of a run: count upward while the next value exists.
        let length = 1
        while (values.has(value + length)) length++
        longest = Math.max(longest, length)
      }
      return longest
    }
    ts
    export default function longestConsecutive(nums: number[]): number {
      // A set makes "is x here?" one step, and drops duplicates for free.
      const values = new Set(nums)
      let longest = 0
      // Loop over the SET, not the array, so each distinct value is visited once.
      for (const value of values) {
        // value - 1 exists, so value is in the middle of a run. Its run gets counted from its start.
        if (values.has(value - 1)) continue
        // value is the start of a run: count upward while the next value exists.
        let length = 1
        while (values.has(value + length)) length++
        longest = Math.max(longest, length)
      }
      return longest
    }
    python
    def longest_consecutive(nums: list[int]) -> int:
        # A set makes "is x here?" one step, and drops duplicates for free.
        values = set(nums)
        longest = 0
        # Loop over the SET, not the list, so each distinct value is visited once.
        for value in values:
            # value - 1 exists, so value is in the middle of a run. Its run gets counted from its start.
            if value - 1 in values:
                continue
            # value is the start of a run: count upward while the next value exists.
            length = 1
            while value + length in values:
                length += 1
            longest = max(longest, length)
        return longest