Find the First and Second Largest Number in JavaScript

When working with arrays in JavaScript, one common interview question is finding the largest and second largest numbers without using built-in sorting methods.

In this blog, we’ll understand the logic step by step with an easy example.

  
let array = [10]

    function findSecondLargestNumber(arr)
    {
      if(arr.length < 2)
      {
        return null;
      }
      let largest = -Infinity;
      let secondLargest = -Infinity;
      for(i=0;i<arr.length;i++)
      {
        if (largest < arr[i])
        {
          secondLargest = largest;
          largest = arr[i];
        }
        else if (secondLargest < arr[i]) {
          secondLargest = arr[i];
        }
      }
      return largest;
    }

    findSecondLargestNumber(array)

Output

9 8
  • Largest Number: 9
  • Second Largest Number: 8

How the Code Works

Step 1: Initialize Variables

let largest = -Infinity;
let secondLargest = -Infinity;

We use -Infinity so that any number in the array will be greater initially.


Step 2: Loop Through the Array

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

We check every element one by one.


Step 3: Update Largest Number

if (largest < arr[i])
{
secondLargest = largest;
largest = arr[i];
}

If the current element is greater than largest:

  • Current largest becomes secondLargest
  • Current element becomes the new largest

Step 4: Update Second Largest Number

else if (secondLargest < arr[i]) {
secondLargest = arr[i];
}

If the number is not larger than largest but is larger than secondLargest, then update secondLargest.


Time Complexity

  • Time Complexity: O(n)
  • Space Complexity: O(1)

This is an optimized solution because we traverse the array only once.



Comments