Home » Java Program » Java program to find Second Largest number in Array

Java program to find Second Largest number in Array

Last updated:

Support this post with a reaction:

4,550 views

Finding the second largest number in an array is a common Java programming problem asked in coding interviews, placement examinations, and technical assessments.

In Java, we can find the second largest element in an array using different approaches, such as:

  1. Using Arrays.sort() method.
  2. Using a single traversal (one-pass approach).
  3. Using two variables to track the largest and second largest elements.

The most efficient approach is the single traversal method, which finds the second largest distinct element in O(n) time complexity without sorting the array.

What Is the Second Largest Number in an Array?

The second largest number in an array is the largest element that is smaller than the maximum element.

For example:

Input:

int[] arr = {4, 3, 2, 6, 5, 3};

Output:

Second largest number = 5

Explanation:

  • Largest number = 6
  • Second largest number = 5

Note: In this tutorial, we consider the second largest distinct number. Duplicate occurrences of the largest number are ignored.

For example, in {10, 10, 8, 5}, the second largest distinct number is 8, not 10.

How to Find the Second Largest Number in Java?

We can solve this problem using the following approaches.

  • Approach 1: Using the sorting method.
  • Approach 2: Using a single traversal (optimal approach).

Approach 1: Find the Second Largest Number Using Arrays.sort()

The Arrays.sort() method in Java sorts an array in ascending order.

After sorting, the largest element will be at the last index. We can traverse the array backward and find the first element that is smaller than the largest element.

import java.util.Arrays;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);

        System.out.println("Enter the size of array:");
        int n = sc.nextInt();

        if (n < 2) {
            System.out.println("Array must contain at least two elements.");
            return;
        }

        int[] arr = new int[n];

        System.out.println("Enter array elements:");

        for (int i = 0; i < n; i++) {
            arr[i] = sc.nextInt();
        }

        Arrays.sort(arr);

        int largest = arr[n - 1];
        boolean found = false;

        for (int i = n - 2; i >= 0; i--) {

            if (arr[i] < largest) {
                System.out.println("Second largest number = " + arr[i]);
                found = true;
                break;
            }
        }

        if (!found) {
            System.out.println("Second largest distinct element does not exist.");
        }

        sc.close();
    }
}

Output

Enter the size of array:
6

Enter array elements:
4 3 2 6 5 3

Second largest number = 5

Explanation of the Program

  1. Import the package: We import java.util.Arrays to use the sort() method and java.util.Scanner to accept input from the user.
  2. Read array elements: The program accepts the array size and elements from the user.
  3. Sort the array: The Arrays.sort(arr) method arranges all elements in ascending order.
  4. Find the largest element: The last element, arr[n-1], represents the largest number.
  5. Find the second largest element: We traverse the sorted array from the second-last index toward the beginning. The first element smaller than the largest element is the second largest distinct number.
  6. Handle duplicate elements: The condition arr[i] < largest skips duplicate occurrences of the largest number.
  7. Handle missing values: If no smaller element is found, the program displays a suitable message.

How Does the Sorting Approach Work?

Consider the following array:

Original Array:
4  3  2  6  5  3

After Sorting:
2  3  3  4  5  6

Largest Element:
6

Second Largest Element:
5

Time Complexity: O(n log n), because sorting takes O(n log n) time.

Space Complexity: Depends on the sorting implementation; Java’s primitive array sorting uses an implementation-dependent amount of auxiliary space.

Approach 2: Find the Second Largest Number Using a Single Traversal

This is the most efficient approach because we can find the second largest element without sorting the array.

We use two variables:

  • largest: Stores the largest element found so far.
  • secondLargest: Stores the second largest distinct element found so far.

We traverse the array only once and update these variables whenever we find a larger or second-largest value.

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);

        System.out.println("Enter the size of array:");
        int n = sc.nextInt();

        if (n < 2) {
            System.out.println("Array must contain at least two elements.");
            return;
        }

        int[] arr = new int[n];

        System.out.println("Enter array elements:");

        for (int i = 0; i < n; i++) {
            arr[i] = sc.nextInt();
        }

        int largest = arr[0];
        int secondLargest = 0;
        boolean found = false;

        for (int i = 1; i < n; i++) {

            if (arr[i] > largest) {
                secondLargest = largest;
                largest = arr[i];
                found = true;
            }
            else if (arr[i] < largest &&
                    (!found || arr[i] > secondLargest)) {

                secondLargest = arr[i];
                found = true;
            }
        }

        if (found) {
            System.out.println("Second largest number = " + secondLargest);
        }
        else {
            System.out.println("Second largest distinct element does not exist.");
        }

        sc.close();
    }
}

Output

Enter the size of array:
6

Enter array elements:
4 3 2 6 5 3

Second largest number = 5

Explanation of the Program

Step 1: Initialize two variables

int largest = arr[0];
int secondLargest = 0;
boolean found = false;
  • largest stores the first array element initially.
  • secondLargest stores the second largest distinct value when found.
  • found indicates whether a second distinct element has been identified.

Step 2: Traverse the array

for (int i = 1; i < n; i++)

We start from index 1 because the first element is already assigned to largest.

Step 3: Check whether the current element is greater than the largest

if (arr[i] > largest) {
    secondLargest = largest;
    largest = arr[i];
    found = true;
}

If the current element is greater than the largest element:

  • The previous largest becomes the second largest.
  • The current element becomes the new largest.
  • We mark that a second distinct element exists.

Step 4: Check whether the current element is between the largest and second largest

else if (arr[i] < largest &&
        (!found || arr[i] > secondLargest)) {

    secondLargest = arr[i];
    found = true;
}

If the current element is smaller than the largest but greater than the current second largest, we update secondLargest.

This condition also prevents duplicate occurrences of the largest element from being considered as the second largest.

Step 5: Print the result

If a second distinct element is found, we print it. Otherwise, we display a message indicating that the second largest distinct element does not exist.

Dry Run: How Does the One-Pass Algorithm Work?

Let’s understand the algorithm using the following array:

int[] arr = {4, 3, 2, 6, 5, 3};

Initially:

  • largest = 4
  • secondLargest = 0
  • found = false

Now, traverse the array element by element.

Current elementLargestSecond largestExplanation
44—Initial element
3433 is smaller than 4
2432 is smaller than 3
6646 becomes largest; 4 becomes second largest
5655 is between 6 and 4
365No update required

Final result

Largest number = 6
Second largest number = 5

Why is the one-pass approach better?

Unlike sorting, this approach does not rearrange the array. It checks every element once and maintains the two largest distinct values.

Therefore, the single traversal approach is preferred for coding interviews and performance-efficient Java programs.

What Are the Edge Cases to Consider?

When writing a Java program to find the second largest number in an array, we should consider the following cases.

Input arrayExpected resultReason
{10, 5, 8, 3}8Normal case
{10, 10, 8, 5}8Duplicate largest values
{5, 5, 5}No second largestAll elements are equal
{-10, -5, -20}-10Negative numbers
{-1, -2, -3}-2All negative numbers
{Integer.MAX_VALUE, 0, -1}0Integer boundary case
{1}Invalid inputOnly one element

The one-pass program above handles these cases, including negative numbers and integer boundary values, without relying on an artificial minimum-value sentinel.