2nd largest from an array| JavaScript Interview question and Answer(2024)

 JavaScript most important question and answer(2024)

JavaScript


2nd Largest from an array

Given an unsorted array of size N with distinct elements. Find the 2nd largest element from the array without sorting the array.

Input Format

The first line contains a single integer N.

The second line consists of N integers of the array.

Output Format

Print the second largest number in the new line.

Example 1

Input

6
3 2 1 5 6 4

Output

5
SOURCE CODE
function SecondLargest(arr, n) {
  // Write code here
    //here find the largest element
    let maxElement=-Infinity;
    for(let i=0;i<arr.length;i++){
        if(arr[i]>maxElement){
            maxElement=arr[i];
        }
    }
    let secondMaxElement=-Infinity;
    for(let i=0;i<arr.length;i++){
        if(arr[i]!=maxElement && arr[i]>secondMaxElement){
            secondMaxElement=arr[i];
        }
    }
    console.log(secondMaxElement);
    
}
Tausif

Hi! My name is Tausif Ahmad. I am a Full Stack Developer at Wipro and a Computer Science graduate from MANUU Hyderabad. I write exam-focused technical blogs and enjoy frontend development, blogging, and creative design.

Post a Comment (0)
Previous Post Next Post