Longest Consecutive Sequence

35 min · longestConsecutive()

Imagine activity-day numbers arriving in a shuffled pile: 12, 9, 11, 10. The order is messy, but the four-day streak is still there.

A consecutive run is a group of integers with no gaps, such as 9, 10, 11, 12. Given an integer array nums, return the length of the longest consecutive run whose values are present in the array.

A few ground rules:

  • The positions in nums don't matter; only the values present matter.
  • Repeated values don't make a run longer.
  • An empty array has no run, so its answer is 0.

Constraints

  • 0 <= nums.length <= 100_000
  • -1_000_000_000 <= nums[i] <= 1_000_000_000

Hints

Ask whether the next value exists

From any value x, you could look for x + 1, then x + 2, and keep walking until you hit a gap. Re-scanning the array for every lookup is the expensive part.

Buy faster membership checks

A hash set is a collection of unique values with fast membership checks. Put all values into one so each "does the next number exist?" question is cheap.

Only begin at a real start

Don't expand from every value. Start at x only when x - 1 is absent; that proves x is the first value of its run. Each present value then belongs to one expansion.

Follow-up

Can you explain why expanding only from run starts keeps the hash-set solution linear, even when the answer itself contains 100,000 values?

Visible cases

Examples

Example 1

ready
Input
nums = [
  100,
  4,
  200,
  1,
  3,
  2
]
Expected
4
Why
1, 2, 3, 4 form the longest run

Example 2

ready
Input
nums = [
  6,
  7,
  7,
  8,
  30,
  31
]
Expected
3
Why
the second 7 doesn't extend the run 6, 7, 8

Example 3

ready
Input
nums = []
Expected
0
Why
an empty array contains no consecutive run

Interview signal

Asked at

AmazonGoogleMeta
Loading editor

Console

ready to run

Ready to run.

3 cases are queued.

Run: visible + custom · Submit: full suite