Find the Second Largest Number in an Array

Problem

Given an integer array, find the second largest number in the array.

Solution

The optimal time is linear to the length of the array N. We can iterate over the array, whenever the largest elements get updated, its current value becomes the second largest.

public static int getSecondLargest(int[] arr){
    int first = Integer.MIN_VALUE;
    int second = Integer.MIN_VALUE;
 
    for(int i=0; i<arr.length; i++){
        if(arr[i]>first){
            second=first;
            first=arr[i];
        }
    }
 
    return second;
}

3 thoughts on “Find the Second Largest Number in an Array”

  1. Your solution will fail for several test cases.


    public static int solution(int[] arr) {
    if(arr.length < 2) {
    return 0;
    }

    if(arr.length == 2) {
    return Math.min(arr[0], arr[1]);
    }

    int largestElementInArray = Integer.MIN_VALUE;
    int secondLargestElementInArray = Integer.MIN_VALUE;

    for (int i = 0; i = largestElementInArray) {
    largestElementInArray = arr[i];
    } else if(arr[i] >= secondLargestElementInArray) {
    secondLargestElementInArray = arr[i];
    }
    }

    return secondLargestElementInArray;
    }

  2. Wont it fail for array [5,4,3,2,1].
    We need to add one more check for condition where second<=arr[i]<=first

Leave a Comment