Second Largest

Medium · rating 1200 · arrays

The first line contains n. The second line contains n integers with at least two distinct values. Print the second largest distinct value.

Constraints: 2 ≤ n ≤ 105

Editorial

Second Largest Element asks for the second-largest distinct value — most elegantly solved in a single pass rather than by sorting.

Approach

Track the largest and second-largest seen so far. For each value: if it beats the largest, the old largest slides into second place; otherwise, if it sits strictly between the two, it becomes the new second.

first = second = -inf
for x in nums:
    if x > first:
        second = first; first = x
    elif first > x > second:
        second = x
return second

Complexity

Time: O(n). Space: O(1) — versus O(n log n) if you sort.

Open Second Largest in Code Arena →