Algorithms and Data Structures · Middle · Question 72 of 75

What does this function do, and what is its complexity?

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

Explanation

A run is counted only from its smallest number (when x - 1 is missing), so every number is checked in the inner loop at most once. Sorting would give O(n log n).

Further reading

Problem with a question

Algorithms and Data Structures · Middle · question 72

Test yourself

Take the Algorithms and Data Structures · Middle quiz: questions and options are shuffled, and you get a review of your mistakes at the end.

Take this quiz