Second Largest Element in an Array
Given an array of integers arr, return the second largest distinct value present in the array. If the array contains fewer than two distinct values — for…
Given an array of integers `arr`, return the second largest distinct value present in the array. If the array contains fewer than two distinct values — for example when all elements are the same, or when only one element exists — return -1. Duplicate copies of the largest value do not count as a distinct second value.
- `1 <= arr.length <= 10^5` - `-10^9 <= arr[i] <= 10^9` - Return -1 if fewer than two distinct values exist in the array. - The interactive visualizer accepts at most 12 values; longer valid arrays are execution-only.
Example 1: input arr = [3, 1, 4, 1, 5]; output 4. The distinct values in descending order are 5, 4, 3, 1. The second largest distinct value is 4.
Example 2: input arr = [5, 5, 5]; output -1. All elements are equal, so there is only one distinct value. No second largest exists; return -1.
Example 3: input arr = [-3, -1, -8, -2]; output -2. The distinct values sorted descending are -1, -2, -3, -8. The second largest is -2.
Category: Arrays. Topic: arrays. Difficulty: Easy. Patterns: linear-scan.