Find the second largest distinct value in an array in a single pass, without sorting. Return null if it does not exist.
function secondLargest(arr) {
let first = -Infinity, second = -Infinity;
for (const n of arr) {
if (n > first) { second = first; first = n; }
else if (n > second && n < first) second = n; // skip duplicates of the maximum
}
return second === -Infinity ? null : second;
}
console.log(secondLargest([12, 35, 1, 10, 34, 1]));
console.log(secondLargest([10, 10, 10]));
console.log(secondLargest([-5, -2, -9]));
console.log(secondLargest([7, 7, 3]));
34 null -5 3
One pass keeps the two largest values seen so far. Starting from -Infinity handles negative numbers, and n < first ignores repeats of the maximum, so [10, 10, 10] has no second largest.