Given an integer array nums, find and return the second largest element in the array in a single pass.
If no second largest element exists (that is, all elements are the same), return -1.
Function Signature
def second_largest(nums: list[int]) -> int:
Rules
-
The second largest element is the largest value that is strictly smaller than the maximum. Extra copies of the maximum do not count, so the second largest element of
[5, 5, 4]
is
4
.
-
Return
-1
when no element is smaller than the maximum, which happens when all elements are equal.
-
-1
can also be a real answer. For
[0, -1]
the second largest element is
-1
, and the function returns
-1
.
Constraints
-
2 <= len(nums) <= 10^5
-
-10^9 <= nums[i] <= 10^9
Examples
Input: nums = [12, 35, 1, 10, 34, 1]
Output: 34
The largest element is 35 and the second largest is 34.
Input: nums = [10, 10, 10]
Output: -1
All elements are the same, so there is no second largest element. Return -1.
Input: nums = [-5, -2, -2, -8]
Output: -5
The maximum, -2, appears twice, and the second copy does not count. The largest value below -2 is -5.