Given an array of numbers, find the second largest distinct value.
This is a favourite because it looks simple and has three traps: duplicates, a single element, and an empty array.
const secondLargest = (numbers) => {
const distinct = [...new Set(numbers)].sort((a, b) => b - a);
return distinct.length > 1 ? distinct[1] : null;
};
console.log(secondLargest([4, 1, 9, 9, 2])); // 4
console.log(secondLargest([1, 1, 1])); // null
console.log(secondLargest([])); // nullWorking through the solution in an interview, the important move is to state the assumptions before you write anything. The word distinct in the question means duplicates do not count, so nine appearing twice is still one value. And the answer does not exist when there are fewer than two distinct values, so returning null is the honest result rather than a made-up number.
Each step of the implementation addresses one of those. The set removes the duplicates while keeping the order, the sort puts them in descending order, and the length check handles the cases where there is no second value. Sorting in descending order means the second element of the array is the answer, which is easy to see and easy to check.
The alternative is a single pass that keeps the two largest values as it goes, which is linear rather than the sort's n times log n, and it avoids allocating a new array. It is also more code and more room for an off-by-one error. If the interviewer mentions performance, mention the single pass version and explain the trade-off, but start with the clear one.