Find the second largest number in an array

Description: Find the second largest number in {12, 35, 1, 10, 34, 1} without sorting the array.

Hint:

  • Keep two variables: largest and second. Update both in one loop.

Solution

public class Main {
    static int secondLargest(int[] a) {
        int largest = Integer.MIN_VALUE, second = Integer.MIN_VALUE;
        for (int n : a) {
            if (n > largest) {
                second = largest;
                largest = n;
            } else if (n > second && n != largest) {
                second = n;
            }
        }
        return second;
    }

    public static void main(String[] args) {
        System.out.println(secondLargest(new int[]{12, 35, 1, 10, 34, 1}));
        System.out.println(secondLargest(new int[]{5, 5, 5, 2}));
    }
}
Output

34
2

How it works

  • When a new biggest value comes, the old biggest becomes the second.
  • n != largest ignores the duplicates of the biggest value.

Read Java Arrays.


Learn more about the similar topics:
Tutorials
No Content Found.
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.