Example 1
ready- Input
nums = [ 100, 4, 200, 1, 3, 2 ]- Expected
4- Why
- 1, 2, 3, 4 form the longest run
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:
nums don't matter; only the values present matter.0.0 <= nums.length <= 100_000-1_000_000_000 <= nums[i] <= 1_000_000_000Hints
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.
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.
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.
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
nums = [
100,
4,
200,
1,
3,
2
]4nums = [
6,
7,
7,
8,
30,
31
]3nums = []0Interview signal
Use the array itself for membership checks. Skip repeated starting values, and begin a
walk only when value - 1 is absent; otherwise, you'd be measuring the middle of a run.
def longest_consecutive(nums: list[int]) -> int:
best = 0
for i, value in enumerate(nums):
if nums.index(value) != i:
continue
if value - 1 in nums:
continue
length = 1
while value + length in nums:
length += 1
best = max(best, length)
return bestThe starts split the distinct values into disjoint runs, so the walks make O(n)
membership queries in total. Each in or index query scans up to n array positions.
Time O(n²) in the worst case. Space O(1) beyond a few counters.
A hash set stores unique values and answers membership questions in O(1) expected time. That removes both problems at once: duplicates disappear, and looking for the next integer no longer scans the array.
def longest_consecutive(nums: list[int]) -> int:
values = set(nums)
best = 0
for value in values:
if value - 1 in values:
continue
length = 1
while value + length in values:
length += 1
best = max(best, length)
return bestThe start test is the key. In a run from 20 through 50, only 20 expands; the other
30 values fail the predecessor test. Across all runs, every distinct value is visited by
exactly one expansion.
Time O(n) expected for building and scanning the set. Space O(n) for its distinct values.
Ready to run.
3 cases are queued.
Visible testcase
Case 1
Expected
4