Find second largest element from an array

1 min read
To find second largest element in an array we need to keep track of largest element and according to that we need to identify second largest element. We need to keep in mind some edge cases as well:
Handle negative numbers
Handle duplicate numbers
Handle if array is empty or array has only 1 element
function findSecondLargest(arr) {
// edge case
if (arr.length < 1 || arr.length === 1) return false;
// logic
let firstLargest = -Infinity;
let secondLargest = -Infinity;
for (let i = 0; i < arr.length; i++) {
if (arr[i] > firstLargest) {
secondLargest = firstLargest
firstLargest = arr[i];
}
else if (arr[i] > secondLargest && arr[i] != firstLargest) {
secondLargest = arr[i];
}
}
return secondLargest;
}
let result = findSecondLargest([5]);
console.log(result);
0
Subscribe to my newsletter
Read articles from Bishal Kumar Shaw directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
