Interview Q&A / Java

IntermediateQuick answerCoding1 min readUpdated 3 Oct 2026

Write Java code to find the second highest distinct number in a list.

SHORT ANSWER

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

java
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.

#java#java8#streams#arrays

Related questions

Practise more Java questions

Test your recall with short answers, then return to the detailed explanations when you need context.

Open Java quick answers →

Get new questions like this by email

One short email when something new and useful lands. No spam, unsubscribe in one tap.

By subscribing you agree to the Privacy Policy.