function longestConsecutive(nums) {const set = new Set(nums);◄
let best = 0;
for (const n of set) { if (!set.has(n - 1)) { // n starts a runlet length = 1;
let cur = n;
while (set.has(cur + 1)) {cur++;
length++;
}
best = Math.max(best, length);
}
}
return best;
}
Sorting would make consecutive numbers neighbours, but that costs O(n log n). Instead, drop every number into a hash set so you can test “is x here?” in O(1).
The key insight: only start counting a run from its true beginning. A number n begins a run exactly when n − 1 is NOT in the set — otherwise n is in the middle of some other run and will be counted from that run’s start.
From a run start, walk forward — n, n+1, n+2, … — using set lookups until the next number is missing, tracking the length.
Because each number is only ever walked over as part of the single run it belongs to, the total work is O(n) even though there is a loop inside a loop.