Find Second Largest Element in an Array
Solve this Problemnums, find and return the second largest distinctDistinctA different value from the largest — duplicates of the largest element don't count as a separate "second largest". element in the array.
If no such element exists — for example, when every value in the array is the same — return -1.
Test Case 1:
Test Case 2:
Test Case 3:
Constraints
- ◆
2 ≤ nums.length ≤ 10⁵ - ◆
-10⁹ ≤ nums[i] ≤ 10⁹ - ◆
If every element is equal, there is no second largest — return -1 in that case
Try the Dry Run
Don't just read the solution — watch it execute, one step at a time.
| 1 | class Solution { |
| 2 | public int findSecondLargest(int[] nums) { |
| 3 | int largest = Integer.MIN_VALUE; |
| 4 | int second = Integer.MIN_VALUE; |
| 5 | for (int i = 0; i < nums.length; i++) { |
| 6 | if (nums[i] > largest) { |
| 7 | second = largest; |
| 8 | largest = nums[i]; |
| 9 | } else if (nums[i] > second && nums[i] != largest) { |
| 10 | second = nums[i]; |
| 11 | } |
| 12 | } |
| 13 | return second == Integer.MIN_VALUE ? -1 : second; |
| 14 | } |
| 15 | } |
| 16 |
-∞-∞Start with both largest and second largest set to negative infinity — nothing has been seen yet. We'll update them as we scan.
Approach & Solutions
Brute Force — Sorting
BruteSort a copy of the array in descending order. The first element is the largest. Walk forward from there until you find a value that's different from it — that's the second largest. If every element is the same, none is ever found and we return -1.
O(n log n)O(n)1class Solution {
2 public int findSecondLargest(int[] nums) {
3 Integer[] sorted = Arrays.stream(nums).boxed().toArray(Integer[]::new);
4 Arrays.sort(sorted, Collections.reverseOrder());
5 for (int i = 1; i < sorted.length; i++) {
6 if (!sorted[i].equals(sorted[0])) {
7 return sorted[i];
8 }
9 }
10 return -1;
11 }
12}Optimal — Single Pass
OptimalTrack both the largest and second largest as you scan once. Whenever a value beats the current largest, the old largest slides down into second before largest takes the new value. Whenever a value beats only the second largest (and isn't equal to the largest), it becomes the new second. One pass, no sorting.
O(n)O(1)1class Solution {
2 public int findSecondLargest(int[] nums) {
3 int largest = Integer.MIN_VALUE;
4 int second = Integer.MIN_VALUE;
5 for (int i = 0; i < nums.length; i++) {
6 if (nums[i] > largest) {
7 second = largest;
8 largest = nums[i];
9 } else if (nums[i] > second && nums[i] != largest) {
10 second = nums[i];
11 }
12 }
13 return second == Integer.MIN_VALUE ? -1 : second;
14 }
15}