Second Largest Element in Array (Java)
In this lesson: Find the second largest element in an array in Java in one pass — code, dry run and output. In Hindi & English.
The problem
Given an array like {10, 5, 20, 8, 15}, the second largest element is 15 (the largest is 20). We can find it in a single pass using just two variables — no sorting needed. This is a common interview question.
The two-variable idea
Keep first (largest) and second (second largest), both starting at the smallest possible value. For each element:
- If it beats
first, the oldfirstbecomessecond, and this becomesfirst. - Else if it beats
second(but not first), it becomessecond.
The Java program
public class SecondLargest {
public static void main(String[] args) {
int[] a = {10, 5, 20, 8, 15};
int first = Integer.MIN_VALUE;
int second = Integer.MIN_VALUE;
for (int x : a) {
if (x > first) {
second = first; // old max slides down
first = x;
} else if (x > second && x != first) {
second = x;
}
}
System.out.println("Second largest: " + second);
}
}
Both start at Integer.MIN_VALUE. Each new maximum pushes the old one into second. Values between the two update only second.
Dry run
| x | x > first? | first | second |
|---|---|---|---|
| Start | — | −∞ | −∞ |
| 10 | yes | 10 | −∞ |
| 5 | no (5>−∞ second) | 10 | 5 |
| 20 | yes | 20 | 10 |
| 8 | no | 20 | 10 |
| 15 | no (15>10) | 20 | 15 |
| Second largest = 15 | |||
When a new biggest appears (20), the old biggest (10) slides into second. Values like 15 that beat second but not first just update second. At the end second = 15.
Why one pass is enough
Because we track both the largest and second largest at the same time, a single loop sees every value once and keeps the two we care about updated. This is O(n) — faster than sorting the whole array (O(n log n)) just to look at the second element, and it does not change the array.
Common mistakes
- Starting variables at 0. Use
Integer.MIN_VALUE, or negative arrays break. - Forgetting to slide first into second. On a new max, move the old max down.
- Counting duplicate maxes. Add
x != firstif you want a distinct second. - Sorting unnecessarily. A single pass is faster and keeps the array intact.
Summary
- The second largest is the biggest value after the maximum.
- Track
firstandsecondin one pass. - A new maximum pushes the old one into
second. - Start both at
Integer.MIN_VALUEfor safety. - This is O(n) — faster than sorting and does not change the array.
Next, sort an array with bubble sort, or remove repeats in remove duplicates from an array.
