Coding problem · Medium · Arrays & Hashing

Longest Consecutive Sequence

Medium Algorithms & data structures Seen at Google, Amazon, Spotify

Given an unsorted array of integers nums, return the length of the longest sequence of consecutive values (e.g. 1,2,3,4). Your algorithm must run in O(n) time.

Example 1

Input: nums = [100,4,200,1,3,2]
Output: 4
Explanation: The sequence is 1, 2, 3, 4.

Example 2

Input: nums = [0,3,7,2,5,8,4,6,0,1]
Output: 9

Constraints

  • 0 <= nums.length <= 10^5

Hints

Hint 1

Sorting is O(n log n). Put everything in a set.

Hint 2

Only start counting from numbers that begin a sequence: x where x−1 is not in the set.

Write and run your solution

Loading the editor… (JavaScript is required to run code in your browser.)

Solution and explanation

Show the solution

Time O(n) · Space O(n)

Load the values into a set. For each value that has no predecessor (x - 1 missing), walk forward while x + 1, x + 2, … exist. Each value is visited at most twice, so the whole thing is linear.

Reference solution

function longestConsecutive(nums) {
  const set = new Set(nums);
  let best = 0;
  for (const x of set) {
    if (set.has(x - 1)) continue;
    let len = 1;
    while (set.has(x + len)) len++;
    best = Math.max(best, len);
  }
  return best;
}