The second highest number
A leaderboard shows only the top name, but the report also wants the runner-up.
- Run the equal values together: 10, 10, 9 has a second largest of 9.
- Fewer than two distinct values gives -1.
second_largest(values: list<int>) → int
Where you start
def second_largest(values: list[int]) -> int:
Worked examples
| Call | Result |
|---|---|
second_largest([3, 1, 2]) | 2 |
second_largest([10, 10, 9]) | 9 |
second_largest([4, 1, 4, 2, 3]) | 3 |
second_largest([5]) | -1 |
Hint
Walk once keeping the two best so far, and ignore a value equal to the current best.
Reference solution in Python
def second_largest(values: list[int]) -> int:
found = False
second = 0
best = 0
started = False
for v in values:
if not started:
best = v
started = True
continue
if v > best:
second = best
found = True
best = v
elif v < best:
if not found or v > second:
second = v
found = True
return second if found else -1