Skip to content
Problem 128 · LeetCode 128(opens in a new tab)

Longest Consecutive Sequence

MediumArrays

You get a list of whole numbers, nums, in no particular order. A consecutive run is a set of values from the list that make an unbroken count, such as 6, 7, 8, 9. The values can sit anywhere in the list.

Return how many values the longest such run holds. A value that appears twice counts once. Aim for O(n) time, so sorting the list is not the intended answer.

Example 1

Input:  nums = [9, 1, 4, 7, 3, 2]
Output: 4
Why:    1, 2, 3, 4 is the longest unbroken run
2 more examples and the constraints

Example 2

Input:  nums = [5, 5, 6, -1, 0]
Output: 2
Why:    5, 6 and -1, 0; the second 5 adds nothing

Example 3

Input:  nums = []
Output: 0
Why:    no numbers, no run

Constraints

  • 0 ≤ length of nums ≤ 100,000
  • Every number is between −1,000,000,000 and 1,000,000,000

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Sort and scanO(n log n)
  2. Hash set, count from run startsO(n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for 100,000 numbersVerdict
Sort and scanO(n log n)
Correct, but misses the O(n) ask
Hash set, count from run startsO(n)
Best; each number touched a few times

n = how many numbers are in the list.

Edge cases to test

  • Empty list. [] has no run at all: return 0, not 1.
  • Repeats. [1, 1, 1] is a run of 1. A repeat must not add to the length.
  • Negative numbers. [-2, -1, 0, 1] is one run of 4 that crosses zero.
  • Far-apart values. [-1,000,000,000, 1,000,000,000] is two runs of 1. Never build an array indexed by value.

Common mistakes

  • Counting up from every number, not just run starts, which makes the loop O(n²) on a long run.
  • Treating a repeated value as a break or as an extra step, instead of ignoring it.
  • Returning 1 for an empty list because best started at 1.

How to talk through it

  1. 1Clarify. Can the list be empty? Do repeated values count once? Is O(n) a hard requirement?
  2. 2Give the sort. Sort and scan in O(n log n); say it misses the O(n) ask.
  3. 3Name the trick. A set gives O(1) membership. A number starts a run only if its predecessor is missing.
  4. 4Code the set loop. Skip non-starts first, then count up. Explain why the total counting work is O(n).
  5. 5Test out loud. Run the empty list, a list of repeats, and a run that crosses zero.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?