Arrays and Hashing Hash map lookups

62. Longest Consecutive Sequence

Medium 147 DSA Sheet

You are given an array of integers nums. Return the length of the longest run of consecutive values that all appear in nums.

A run of consecutive values is a list of whole numbers where each one is exactly one more than the one before, such as 4, 5, 6, 7. The values of a run can sit anywhere in nums, in any order. A value that appears more than once counts only once.

Example 1

Input: nums = [8, 3, 10, 4, 9, 1, 2, 11, 7]

Output: 5

Explanation: 7, 8, 9, 10 and 11 all appear, so they form a run of length 5. 1, 2, 3 and 4 form a shorter run of length 4.

Example 2

Input: nums = [0, -1, 2, -2, 1, 1, 0]

Output: 5

Explanation: Every value from −2 to 2 appears, which is a run of length 5. The repeated 0 and 1 count once each, so they do not make the run longer.

Example 3

Input: nums = [1000000000, -1000000000, 999999999]

Output: 2

Explanation: 999999999 and 109 form a run of length 2. −109 has no neighbour in the array, so on its own it is a run of length 1.

Check your understanding

Work out the answer for this input before you write any code.

nums = [1, 2, 2, 3]

Constraints

  • 0 ≤ nums.length ≤ 105
  • -109 ≤ nums[i] ≤ 109

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.