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;
}- ✓Correct answer: Longest run of consecutive numbers, O(n)
- 2Number of duplicates, O(n²)
- 3Largest number in the array, O(n log n)
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).