Find second largest element from an array

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:

  1. Handle negative numbers

  2. Handle duplicate numbers

  3. 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

Bishal Kumar Shaw
Bishal Kumar Shaw