The Find Second Largest Number in Array algorithm question was asked in many interviews including FAANG companies.

The question for an algorithm is,

Given an array of numbers and the task is to find the second-largest number in the array.

Example 1:

Input: array = {12, 35, 1, 10, 34, 1}

Output: 34

Explanation: As we can see 35 is the first largest number in the array after that largest number is 34. So, 34 is the second largest number in the array.

var secondLargest = function(array){

let first=0;

let second=0;

for(i=0;i<array.length;i++)

{

if(first<array[i])

{

first=array[i];

}

}

for(i=0;i<array.length;i++)

{

if (array[i] > second && array[i] < first)

{

second=array[i];

}

}

return second;

}

Here, One of the most basic or simple solutions can be running two loops. The first loop will find the first largest element in the array (let's say first is the largest element present in the array). After that, the second loop will find the largest element present in the array which is smaller than first. So, in this way, we can find second largest element in array.

I hope you understood the algorithm. If you have any doubts, please let us know in the comments.