00:00

Problem Statement

Input/Output Examples

Visual Explanation

distinct() must come before skip(1); otherwise the duplicate 45 would be returned as the "second highest". findFirst() returns an empty Optional when nothing is left.

Approaches

The stream version is short and declarative. The loop version, shown for comparison, finds the answer in one pass.

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.

Complexity Analysis

Here n is the size of the list. The stream sorts the distinct values; the loop reads each value once with two variables.

Interview Tips and Recommended Approach

  • Call distinct() first. Without it, [45, 45, 30] would return 45.
  • Return an Optional. It makes the "no answer" case explicit instead of using a magic number.
  • Mention the complexity trade-off. Sorting is O(n log n); a single pass is O(n).
  • Generalise with skip(k - 1) for the k-th highest value.

Recommended Approach: distinct(), sorted() and skip()

Why: it is the idiomatic Stream API answer: short, safe for every input and easy to adapt to the k-th highest value.