Second Largest Element - Problem
Given an array of integers, find the second largest element without sorting the array. The array may contain duplicates.
You need to handle edge cases where:
- All elements are the same
- Array has only two elements
- Multiple elements have the same maximum value
Return the second largest distinct value. If no second largest element exists, return -1.
Input & Output
Example 1 — Basic Case
$
Input:
nums = [3, 1, 4, 1, 5, 9, 2]
›
Output:
5
💡 Note:
The largest element is 9, and the second largest distinct element is 5
Example 2 — With Duplicates
$
Input:
nums = [2, 2, 1, 3]
›
Output:
2
💡 Note:
The largest element is 3, and the second largest distinct element is 2
Example 3 — All Same Elements
$
Input:
nums = [1, 1, 1, 1]
›
Output:
-1
💡 Note:
All elements are the same, so no second largest distinct element exists
Constraints
- 2 ≤ nums.length ≤ 104
- -109 ≤ nums[i] ≤ 109
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code