TypeScript: Find the Second Largest Element in an Array

1. Introduction

Finding the second largest element in an array is a common coding problem. The problem can be solved using various approaches, with different time complexities. One simple method involves sorting the array and picking the second last element, but this can be inefficient with a larger dataset. Instead, we'll be using a single-pass method that is more efficient.

2. Program Overview

In this program, we will iterate through the array to find the largest and second-largest elements in a single pass.

3. Code Program

// Function to find the second largest element in an array
function findSecondLargest(arr: number[]): number | null {
    if (arr.length < 2) return null; // Array should have at least two elements

    let firstLargest = -Infinity;  // Initialized to the smallest possible value
    let secondLargest = -Infinity; // Initialized to the smallest possible value

    for (let num of arr) {
        if (num > firstLargest) {
            secondLargest = firstLargest;
            firstLargest = num;
        } else if (num > secondLargest && num !== firstLargest) {
            secondLargest = num;
        }
    }

    if (secondLargest === -Infinity) return null; // Means no valid second largest element
    return secondLargest;
}

// Test the function
const testArray = [10, 5, 8, 20, 7, 15];
const result = findSecondLargest(testArray);
if (result !== null) {
    console.log(`The second largest element in the array is: ${result}`);
} else {
    console.log('The array does not have a valid second largest element.');
}

4. Step By Step Explanation

1. We first check if the array length is less than 2. If so, it's not possible to have a second largest element, so we return null.

2. firstLargest and secondLargest variables are initialized with the smallest possible value (-Infinity), which ensures that any real number from the array will be larger than this initial value.

3. We iterate through each number in the array:

  • If the current number (num) is greater than firstLargest, we move the current value of firstLargest to secondLargest and update firstLargest with the current number.
  • If the current number is greater than secondLargest but not equal to firstLargest, we update secondLargest.

4. After iterating through the array, if secondLargest is still -Infinity, this means there's no valid second largest element (i.e., all numbers in the array are the same), so we return null.

5. Otherwise, we return the value of secondLargest.

Comments