Track the highest and second-highest values in a single pass. When a number is larger than the current highest, the old highest becomes the second-highest.
public class SecondHighest {
static Integer secondHighest(int[] nums) {
Integer first = null, second = null;
for (int num : nums) {
if (first == null || num > first) {
second = first;
first = num;
} else if (num != first && (second == null || num > second)) {
second = num;
}
}
return second; // null when there is no second distinct value
}
public static void main(String[] args) {
System.out.println(secondHighest(new int[] {12, 35, 1, 10, 34, 1}));
System.out.println(secondHighest(new int[] {10, 10, 5}));
System.out.println(secondHighest(new int[] {7, 7, 7}));
}
}34
5
null
With streams: Arrays.stream(nums).boxed().distinct().sorted(Comparator.reverseOrder()).skip(1).findFirst(), which is shorter but O(n log n).
Always ask how duplicates should be treated; it is the follow-up interviewers use to see if you clarify requirements.
A concise interview answer is
I scan the array once keeping the highest and second-highest values: when a number beats the highest, the old highest moves to second; otherwise it replaces second if it is bigger and not equal to the highest. That is O(n) time and O(1) space and correctly ignores duplicates of the maximum.
Last updated: 11 November 2026
Previous question: Write a Java program to find the duplicate characters in a string.
Next question: Write a Java program to check whether a number is an Armstrong number.