Java Array Program · A11
Find the Second Largest Element in an Array in Java
Keep two values while scanning: the largest so far and the second largest. The details are in the duplicates: a repeated maximum is not a second value.
Problem Statement
Write a method that returns the second largest distinct value in an int array, without sorting it.
If there is no second distinct value, for example when every element is equal, return an empty OptionalInt (printed as none).
Input/Output Examples
[7, 42, 13, 42, 9]Output13Explanation: the second 42 is a repeat of the largest value, so 13 is second.[5, 5, 5]OutputnoneExplanation: there is only one distinct value.[-1, -7]Output-7Explanation: -1 is the largest, so -7 is second.Visual Explanation
[7, 42, 13, 42, 9]: a new maximum pushes the old one into second place (purple); a value between the two replaces the second (amber); a repeat of the maximum changes nothing.The condition n < first in the second branch is what ignores repeats of the maximum. Without it, the second 42 would wrongly become the answer.
Approaches
Both approaches avoid sorting. One finds both values in a single pass; the other uses two simpler passes.
Approach 1: One Pass, Two Variables (Recommended)
Idea: track the largest and second largest distinct values; boolean flags record whether each has been set.
- If
nis larger thanfirst, movefirstintosecondand storenasfirst. - Else, if
n < firstandnis larger thansecond, store it assecond. - Return
secondif it was ever set.
Time: O(n) · Space: O(1).
Approach 2: Two Passes
Idea: find the maximum first, then find the largest value that is strictly smaller than it.
- Pass 1: compute the maximum.
- Pass 2: track the largest value below the maximum.
- Return it, or an empty result if none exists.
Time: O(n) · Space: O(1).
Java Solutions
Each tab is a complete program that runs on Java 17 or later. Both programs print the same output for the same inputs.
Approach 1: One Pass, Two Variables (Recommended)
Flags instead of Integer.MIN_VALUE sentinels mean the method also works when the real answer is Integer.MIN_VALUE.
import java.util.Arrays;
import java.util.OptionalInt;
public class SecondLargestOnePass {
// Tracks the largest and second largest DISTINCT values in one pass
static OptionalInt secondLargest(int[] arr) {
boolean hasFirst = false;
boolean hasSecond = false;
int first = 0;
int second = 0;
for (int n : arr) {
if (!hasFirst || n > first) {
if (hasFirst) {
second = first;
hasSecond = true;
}
first = n;
hasFirst = true;
} else if (n < first && (!hasSecond || n > second)) {
second = n;
hasSecond = true;
}
}
return hasSecond ? OptionalInt.of(second) : OptionalInt.empty();
}
public static void main(String[] args) {
int[][] inputs = {{7, 42, 13, 42, 9}, {5, 5, 5}, {-1, -7}};
for (int[] arr : inputs) {
OptionalInt r = secondLargest(arr);
System.out.println(Arrays.toString(arr) + " -> " + (r.isPresent() ? r.getAsInt() : "none"));
}
}
}
[7, 42, 13, 42, 9] -> 13 [5, 5, 5] -> none [-1, -7] -> -7
Time complexity: O(n) · Space complexity: O(1).
Approach 2: Two Passes
Each pass is trivial to verify, which makes this a good fallback if the one-pass logic feels risky.
import java.util.Arrays;
import java.util.OptionalInt;
public class SecondLargestTwoPass {
// Pass 1 finds the maximum; pass 2 finds the largest value that is smaller than it
static OptionalInt secondLargest(int[] arr) {
if (arr.length == 0) {
return OptionalInt.empty();
}
int max = arr[0];
for (int n : arr) {
max = Math.max(max, n);
}
boolean found = false;
int second = 0;
for (int n : arr) {
if (n < max && (!found || n > second)) {
second = n;
found = true;
}
}
return found ? OptionalInt.of(second) : OptionalInt.empty();
}
public static void main(String[] args) {
int[][] inputs = {{7, 42, 13, 42, 9}, {5, 5, 5}, {-1, -7}};
for (int[] arr : inputs) {
OptionalInt r = secondLargest(arr);
System.out.println(Arrays.toString(arr) + " -> " + (r.isPresent() ? r.getAsInt() : "none"));
}
}
}
[7, 42, 13, 42, 9] -> 13 [5, 5, 5] -> none [-1, -7] -> -7
Time complexity: O(n) · Space complexity: O(1).
Complexity Analysis
| Approach | Time Complexity | Space Complexity |
|---|---|---|
| One Pass, Two Variables | O(n) | O(1) |
| Two Passes | O(n) | O(1) |
Here n is the number of elements. Both approaches are linear with constant extra memory; sorting would cost O(n log n).
Interview Tips and Recommended Approach
- Clarify duplicates. Is the second largest of
[42, 42, 13]42 or 13? "Distinct" means 13. - Avoid sentinel bugs. Starting
secondatInteger.MIN_VALUEcannot tell "no answer" from a realMIN_VALUE. - Do not sort just for this. Sorting is slower and changes the array unless you copy it.
- Generalise carefully. For the k-th largest, a min-heap of size
kis the usual answer.
Recommended Approach: One Pass, Two Variables
Why: it reads the array once with two variables and handles duplicates and negative numbers without special sentinel values.