Second Largest Element in Java: Solution, Explanation & Practice

Find the second largest element

Problem summary

Write a program that finds the second largest element in an array.

Starter code

public class Main {
    public static void main(String[] args) {
        int[] arr = {12, 35, 1, 10, 34, 1}; // Test case 1
        
        // Find second largest
        // Print: Second largest: <result>
    }
}

Expected output and test cases

  • Second largest in array
    Second largest: 34
  • From [1,2,3,4,5]
    Second largest: 4
  • From [9,9,9,9]
    Second largest: 9

Hints

  1. Track both largest and second largest
  2. Update both as you iterate
  3. Handle duplicates carefully

Validated solution

Reveal Java solution
public class Main {
    static int secondLargestDistinct(int[] values) {
        Integer largest = null;
        Integer second = null;
        for (int value : values) {
            if (largest == null || value > largest) {
                second = largest;
                largest = value;
            } else if (value != largest && (second == null || value > second)) {
                second = value;
            }
        }
        if (second == null) throw new IllegalArgumentException("need two distinct values");
        return second;
    }

    public static void main(String[] args) {
        System.out.println("Second largest: " + secondLargestDistinct(new int[] {12, 45, 9, 34, 18}));
    }
}

How to approach the problem

Track the largest and second-largest distinct values in one pass. A new largest pushes the old largest into second place; a duplicate of the largest must not become the answer.

Approach

  1. Represent missing candidates explicitly.
  2. Promote the old largest when a new largest arrives.
  3. Update second only for a distinct in-between value.

Time and space complexity

Time: O(n). Space: O(1).

Edge cases to test

  • All-equal arrays have no second distinct value.
  • Negative values work because no numeric sentinel is used.

Common mistakes

  • Sorting only to find two values when input order need not change.
  • Treating a duplicate maximum as second largest.

Follow-up challenge

Return the k-th distinct largest value using a bounded min-heap.

Related Arrays exercises

Practice all Arrays exercises · Run this idea in the Java compiler