Write Java code to find the second highest distinct number in a list.
Sort the distinct values in descending order, skip the first, and take the next, returning an Optional because there may be no second value. The stream version is O(n log n); a single loop tracking two maximums is O(n).
Explain it simply
In a class with marks 90, 90 and 85, the second highest mark is 85, not 90. So we must ignore repeats before we pick.
Line by line
import java.util.*;
public static Optional<Integer> secondHighest(List<Integer> nums) {
return nums.stream()
.distinct()
.sorted(Comparator.reverseOrder())
.skip(1)
.findFirst();
}
// secondHighest(List.of(90, 90, 85, 70)) returns Optional[85]
// secondHighest(List.of(5, 5)) returns Optional.empty
// Single pass, no sorting:
public static Integer secondHighestLoop(int[] a) {
Integer first = null, second = null;
for (int x : a) {
if (first == null || x > first) { second = first; first = x; }
else if (x != first && (second == null || x > second)) { second = x; }
}
return second; // null if there is no second distinct value
}Complexity
Stream version: time O(n log n), space O(n). Loop version: time O(n), space O(1).
What to say in the interview
"I clarify whether duplicates count. The stream pipeline is clearest, and returning Optional handles lists with fewer than two distinct values. If the interviewer wants better than n log n, I switch to the single-pass loop with two trackers."
Common mistakes
- Skipping the distinct step and returning the maximum twice.
- Not handling the case where the list has fewer than two distinct values.