Find Second largest element in an array in Javascript

Find Second largest element in an array in Javascript

Arrays, Data Structure, Javascript

This program is to find second largest element in an array in Javascript. This was asked in PaisaBazaar interview and i have solved it perfectly. So i thought to share my approch with you guys.

Input: arr[] = {12, 35, 1, 10, 34, 1}

Output: The second largest element is 34.

Simple Approch you can use in this case is to sort the array first using sorting algorithm and then print the last second element. But this is not efficient approach

  1. Initialize two variables first and second to INT_MIN as
    first = second = INT_MIN
  2. Start traversing the array,
    a) If the current element in array say arr[i] is greater
    than first. Then update first and second as,
    second = first
    first = arr[i]
    b) If the current element is in between first and second,
    then update second to store the value of current variable as
    second = arr[i]
  3. Return the value stored in second.
function findSecondLargestElem(arr){
    let first = -1 , second = -1;

    for(let i = 0; i <= arr.length-1; i++){
        if(arr[i] > first){
            second = first;
            first = arr[i];
        }
        else if( arr[i] > second && arr[i] != first){
            second = arr[i];
        }
    }
    console.log(second);
}
let arr = [12, 35, 1, 10, 34, 1]
findSecondLargestElem(arr);
  • Time Complexity: O(n). 
    Only one traversal of the array is needed.
  • Auxiliary space: O(1). 
    As no extra space is required.

References: https://www.geeksforgeeks.org/find-second-largest-element-array/

Leave a Reply