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 have completed B.Tech in Computer Science from Maulana Azad National Urdu University Hyderabad. I am always ready to have new experiences meet new people and learn new things. 1. I am very interested in Frontend Development. 2. I love video editing and graphics designing. 3. I enjoy challenges that enables to grow. 4. I am part time Blogger.

Post a Comment (0)
Previous Post Next Post