AceYourInterviews
Checking sign-in…

6. Longest Consecutive Sequence

IntermediateHashing and boundary detection

Find the longest sequence of integer values that increase by exactly one. The values may be scattered throughout the input; you are measuring a run of values, not a continuous slice of the array.

Repeated occurrences of the same value do not extend a run. For example, the values 1, 2, 3, and 4 form a length-four run regardless of their input order.

Example 1

Input

[100,4,200,1,3,2]

Output

4

Explanation: The values 1,2,3,4 form a run of length four even though they are scattered through the array.

Example 2

Input

[1,2,2,3]

Output

3

Explanation: The repeated 2 does not lengthen or break the run 1,2,3.

Example 3

Input

[-2147483648,2147483647]

Output

1

Explanation: The two extreme int values must not wrap around and appear consecutive.

Constraints

  • 0 <= nums.length <= 105
  • -231 <= nums[i] <= 231 - 1
Hints
Hint 1

Which operation do you repeat when extending a consecutive run? Store membership rather than input positions.

Hint 2

Every run has a unique smallest value. How can you recognize it without sorting?

Hint 3

Only launch scans from values whose predecessor is absent. Iterate distinct values and guard integer boundaries.

Practice on LeetCode ↗
Code
Saved on this deviceLn 1, Col 1

Scattered run

[100,4,200,1,3,2]
4