00:00

Problem Statement

Input/Output Examples

Visual Explanation

The condition n < first in the second branch is what ignores repeats of the maximum. Without it, the second 42 would wrongly become the answer.

Approaches

Both approaches avoid sorting. One finds both values in a single pass; the other uses two simpler passes.

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 number of elements. Both approaches are linear with constant extra memory; sorting would cost O(n log n).

Interview Tips and Recommended Approach

  • Clarify duplicates. Is the second largest of [42, 42, 13] 42 or 13? "Distinct" means 13.
  • Avoid sentinel bugs. Starting second at Integer.MIN_VALUE cannot tell "no answer" from a real MIN_VALUE.
  • Do not sort just for this. Sorting is slower and changes the array unless you copy it.
  • Generalise carefully. For the k-th largest, a min-heap of size k is the usual answer.

Recommended Approach: One Pass, Two Variables

Why: it reads the array once with two variables and handles duplicates and negative numbers without special sentinel values.