Skip to main content

12. Longest Consecutive Sequence

mediumAsked at Adyen

Find the length of the longest run of consecutive integers in an unsorted array.

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. The algorithm must run 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 runs.

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

Tradeoff:

2. Hash set starts-only expansion

Only expand from a number whose predecessor is absent.

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

Tradeoff:

Adyen-specific tips

Adyen relates this to detecting card-testing fraud runs — they want the starts-only optimization to surface, since brute expansion would burn rate-limited fraud-signal budget.

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 Adyen interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.

Practice these live with InterviewChamp.AI →