0
0
JavaProgramBeginner · 2 min read

Java Program to Find Second Largest Element in Array

To find the second largest element in an array in Java, iterate through the array keeping track of the largest and second largest values using if conditions, for example: if (arr[i] > largest) { secondLargest = largest; largest = arr[i]; } else if (arr[i] > secondLargest && arr[i] != largest) { secondLargest = arr[i]; }.
📋

Examples

Input[10, 20, 30, 40, 50]
Output40
Input[5, 5, 5, 5]
OutputNo second largest element
Input[12, 35, 1, 10, 34, 1]
Output34
🧠

How to Think About It

To find the second largest number, first find the largest number by comparing each element. Then track the next largest number that is smaller than the largest. This way, you keep updating two variables as you scan the array once.
📐

Algorithm

1
Initialize two variables largest and secondLargest with minimum possible values.
2
Loop through each element in the array.
3
If current element is greater than largest, update secondLargest to largest and largest to current element.
4
Else if current element is greater than secondLargest and not equal to largest, update secondLargest to current element.
5
After the loop, check if secondLargest was updated; if not, there is no second largest element.
6
Return or print the secondLargest value.
💻

Code

java
public class SecondLargest {
    public static void main(String[] args) {
        int[] arr = {12, 35, 1, 10, 34, 1};
        int largest = Integer.MIN_VALUE;
        int secondLargest = Integer.MIN_VALUE;
        for (int num : arr) {
            if (num > largest) {
                secondLargest = largest;
                largest = num;
            } else if (num > secondLargest && num != largest) {
                secondLargest = num;
            }
        }
        if (secondLargest == Integer.MIN_VALUE) {
            System.out.println("No second largest element");
        } else {
            System.out.println("Second largest element is " + secondLargest);
        }
    }
}
Output
Second largest element is 34
🔍

Dry Run

Let's trace the array [12, 35, 1, 10, 34, 1] through the code

1

Initialize

largest = Integer.MIN_VALUE, secondLargest = Integer.MIN_VALUE

2

Check 12

12 > largest(-2147483648), so secondLargest = largest(-2147483648), largest = 12

3

Check 35

35 > largest(12), so secondLargest = 12, largest = 35

4

Check 1

1 > secondLargest(12)? No, no change

5

Check 10

10 > secondLargest(12)? No, no change

6

Check 34

34 > secondLargest(12) and 34 != largest(35), so secondLargest = 34

7

Check 1

1 > secondLargest(34)? No, no change

8

Result

secondLargest = 34

IterationCurrent NumberLargestSecond Largest
11212-2147483648
2353512
313512
4103512
5343534
613534
💡

Why This Works

Step 1: Track largest and second largest

We keep two variables to remember the biggest and the second biggest numbers found so far.

Step 2: Update when bigger found

If a number is bigger than the largest, it becomes the new largest and the old largest becomes second largest.

Step 3: Update second largest carefully

If a number is not bigger than largest but bigger than second largest and not equal to largest, update second largest.

Step 4: Check if second largest exists

If second largest never changed from initial minimum, it means no second largest element exists.

🔄

Alternative Approaches

Sort the array and pick second last element
java
import java.util.Arrays;
public class SecondLargestSort {
    public static void main(String[] args) {
        int[] arr = {12, 35, 1, 10, 34, 1};
        Arrays.sort(arr);
        int n = arr.length;
        int largest = arr[n-1];
        int secondLargest = Integer.MIN_VALUE;
        for (int i = n-2; i >= 0; i--) {
            if (arr[i] != largest) {
                secondLargest = arr[i];
                break;
            }
        }
        if (secondLargest == Integer.MIN_VALUE) {
            System.out.println("No second largest element");
        } else {
            System.out.println("Second largest element is " + secondLargest);
        }
    }
}
This method is simple but slower because sorting takes O(n log n) time.
Use a TreeSet to store unique elements and get second last
java
import java.util.TreeSet;
public class SecondLargestTreeSet {
    public static void main(String[] args) {
        int[] arr = {12, 35, 1, 10, 34, 1};
        TreeSet<Integer> set = new TreeSet<>();
        for (int num : arr) {
            set.add(num);
        }
        if (set.size() < 2) {
            System.out.println("No second largest element");
        } else {
            set.pollLast(); // remove largest
            System.out.println("Second largest element is " + set.last());
        }
    }
}
This approach handles duplicates easily but uses extra memory and has O(n log n) time due to TreeSet operations.

Complexity: O(n) time, O(1) space

Time Complexity

The program loops through the array once, so it takes linear time proportional to the number of elements, O(n).

Space Complexity

Only a few variables are used to track largest and second largest, so space is constant, O(1).

Which Approach is Fastest?

The single pass method is fastest with O(n) time and O(1) space, while sorting or TreeSet methods are slower due to O(n log n) time.

ApproachTimeSpaceBest For
Single pass scanO(n)O(1)Fastest and simplest for large arrays
Sorting arrayO(n log n)O(1)Simple but slower, useful if array needs sorting anyway
TreeSet methodO(n log n)O(n)Handles duplicates easily, but uses extra memory
💡
Always check for arrays with all equal elements to avoid incorrect second largest results.
⚠️
Beginners often forget to handle the case when all elements are equal, causing wrong output or errors.