Second Largest Element

Easy~10 min

Given an array of integers nums with at least one element, return the second largest distinct element. If no second distinct element exists, return -1.

For example, given [3, 1, 4, 1, 5, 9], the largest is 9 and the second largest distinct value is 5.

Given [7, 7, 7], all elements are the same so there is no second distinct element — return -1.

Examples

Example 1
Input: nums = [3, 1, 4, 1, 5, 9]
Output: 5
Explanation: The distinct values sorted descending are [9, 5, 4, 3, 1]. The second is 5.
Example 2
Input: nums = [7, 7, 7]
Output: -1
Explanation: Only one distinct value (7) exists, so there is no second largest.
Example 3
Input: nums = [10, 5]
Output: 5
Explanation: Two distinct values: 10 and 5. The second largest is 5.

Constraints

  • 1 <= nums.length <= 10^5
  • -10^9 <= nums[i] <= 10^9
Code
Ctrl+EnterRun|Ctrl+⇧+EnterSubmit
Output

Run your code to see results

Use Cmd+Enter to run