Skip to main content

21. Longest Consecutive Sequence

mediumAsked at Chegg

Find the longest consecutive integer sequence in O(n) using a hash set — Chegg applies this pattern when detecting sequential gaps in student progress data.

By Alex Chen, Founder, InterviewChamp.AI · Last verified

Problem

Given an unsorted array of integers nums, return the length of the longest consecutive elements sequence. You must write an algorithm that runs in O(n) time.

Constraints

  • 0 <= nums.length <= 10^5
  • -10^9 <= nums[i] <= 10^9

Examples

Example 1

Input
nums = [100,4,200,1,3,2]
Output
4

Example 2

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

Approaches

1. Sort then scan

Sort and count consecutive run length — O(n log n) and disqualified by the O(n) constraint.

Time
O(n log n)
Space
O(1)
function longestConsecutive(nums) {
  if (!nums.length) return 0;
  nums.sort((a, b) => a - b);
  let max = 1, cur = 1;
  for (let i = 1; i < nums.length; i++) {
    if (nums[i] === nums[i-1]) continue;
    cur = nums[i] === nums[i-1] + 1 ? cur + 1 : 1;
    max = Math.max(max, cur);
  }
  return max;
}

Tradeoff:

2. Hash set with sequence-start detection

Load all numbers into a Set; only begin counting from numbers where n-1 is absent (sequence starts). Each element is visited at most twice — O(n) total.

Time
O(n)
Space
O(n)
function longestConsecutive(nums) {
  const set = new Set(nums);
  let max = 0;
  for (const num of set) {
    if (!set.has(num - 1)) {
      let cur = num, len = 1;
      while (set.has(cur + 1)) { cur++; len++; }
      max = Math.max(max, len);
    }
  }
  return max;
}

Tradeoff:

Chegg-specific tips

Chegg interviewers will ask why you iterate over the set rather than the array — explain that duplicate values in the array are deduplicated, preventing double-counting sequence starts.

Solve it now

Free. No sign-up. Python and JavaScript run instantly in your browser.

Output

Press Run or Cmd+Enter to execute

Practice these live with InterviewChamp.AI

Drill Longest Consecutive Sequence and other Chegg interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.

Practice these live with InterviewChamp.AI →