Given an array of numbers, find the second largest distinct value.
This question comes up often because it looks simple, but it has three traps. The first trap is duplicate values, the second is an array with only one item, and the third is an empty array.
function secondLargest(numbers) {
// Remove the duplicates and sort from the biggest to the smallest.
var distinct = [];
for (var i = 0; i < numbers.length; i++) {
if (distinct.indexOf(numbers[i]) === -1) {
distinct.push(numbers[i]);
}
}
distinct.sort(function (a, b) {
return b - a;
});
if (distinct.length < 2) {
return null;
}
return distinct[1];
}
console.log(secondLargest([4, 1, 9, 9, 2])); // 4
console.log(secondLargest([1, 1, 1])); // null
console.log(secondLargest([])); // nullWhen you answer this in an interview, the most important step happens before you write any code. You say your assumptions out loud. The word "distinct" in the question means that duplicates do not count, so a nine that appears twice is still one value. And the answer does not exist when the array has fewer than two different values, so returning null is the honest answer instead of a made-up number.
Each step of the code above handles one of those traps. The loop that collects the values removes the duplicates. The sort puts the values in descending order, which means the second item in the array is the answer you want. The length check handles the cases where there is no second value at all.
There is another way to solve this. You can walk through the array once and keep the two largest values as you go. That version is faster, because sorting takes n times log n steps while a single pass takes n steps, and it does not need a new array. It is also more code and more room for an off-by-one mistake. If the interviewer asks about performance, mention the single pass version and explain the trade-off, but start with the clear one.