Second Largest

easy

Given an array arr of positive integers, return the second largest element in it.

The second largest must be strictly smaller than the largest — if the maximum value appears more than once, those extra copies do not count as the runner-up. For arr = [10, 5, 10] the largest is 10 and the second largest is 5.

If no valid second largest exists (for example, when every value is identical), return -1.

Hints

You want the runner-up, not the winner. Beware the trap: if you just take the max, delete it, and take the max again, what happens when the max appeared twice?
The second largest must be strictly smaller than the largest — extra copies of the champion don't count.
Sweep once while carrying two values: the largest so far and the best value strictly below it. When a new champion appears, the old champion slides down into second place.

Common doubts

Return -1. Every element equals the largest, so there is no element strictly smaller than it — no valid second largest exists.
A different value. In [10, 5, 10] the largest is 10 and the second largest is 5 — the duplicate 10 is ignored.
Values are guaranteed >= 1, so -1 is a safe 'nobody yet' sentinel. If no valid runner-up is found, second stays -1, which is exactly the answer the problem asks for.

Interview follow-ups

Generalize the podium idea to k trackers, use a size-k min-heap for an O(n log k) scan, or Quickselect for the k-th order statistic in O(n) average time.
Drop the 'strictly smaller' rule and allow equality when tracking the top two, so [10, 10, 5] would return 10. Clarify this with the interviewer before coding.

Fun facts

  • The single-pass two-variable trick is just the 'running maximum' pattern carrying a podium of the top two instead of only the gold medalist.
  • This 'top-two in one sweep' idea powers streaming systems that keep the two highest bids, temperatures, or scores without ever storing the full data.

Asked at

AmazonGoogleMicrosoftAdobeFlipkart
Frequently Sometimes Occasionally
Example 1
Input: arr = [12, 35, 1, 10, 34, 1]
Output: 34
The largest element is 35 and the next distinct value below it is 34.
Example 2
Input: arr = [10, 5, 10]
Output: 5
The largest is 10; ignoring its duplicate, the second largest is 5.
Example 3
Input: arr = [10, 10, 10]
Output: -1
Every value equals the largest, so no strictly-smaller second largest exists.
Constraints

- 2 <= arr.size <= 10^5 - 1 <= arr[i] <= 10^5

Solve this problem →