Second Largest Element in an Array
Second Largest Element in an Array is a easy arrays & hashing problem solved with the sorting pattern.
The best approach, optimal (one pass with two trackers), runs in O(n) time and O(1) space.
Below are 3 approaches in Java, Python, C++ and JavaScript, from brute force (sort, then walk back from the end) up.
Problem
You are given an array arr of positive integers. Return the second largest distinct value in it: the biggest value that is strictly smaller than the maximum.
Copies of the maximum do not count, so in [10, 5, 10] the answer is 5, not 10. If no value is strictly smaller than the maximum (the array has one element, or every element is the same), return -1.
Examples
Example 1
- Input
arr = [12, 35, 1, 10, 34, 1]- Output
34- Why
- The largest value is 35. The biggest value below it is 34.
Example 2
- Input
arr = [10, 5, 10]- Output
5- Why
- The maximum 10 appears twice, and a repeat of the maximum does not count as the second largest. The answer is the largest value strictly smaller than 10, which is 5.
Example 3
- Input
arr = [10, 10, 10]- Output
-1- Why
- Every value equals the maximum, so no value is strictly smaller than it.
Constraints
1 <= arr.length <= 10^51 <= arr[i] <= 10^5
Solve it here
Write your solution in Java, Python, C++ or JavaScript and run it against the examples, right in the page. Submit runs the hidden tests too and, with a free account, records the solve in your revision log.
Your own testcases: Run checks these, and the expected output comes from our reference solution.
My submissions
Nothing yet. Every Run and Submit you make while signed in shows up here.
| When | Result | Tests | Runtime | Your time | Type |
|---|
Run checks the testcases above (3 examples, or your own). Submit also runs 15 hidden tests and saves the solve to your log. Signed in, every Run and Submit is saved under My submissions; your draft stays in this browser.
Animated walkthrough
A narrated, step-by-step animation that builds the solution from the idea up. Press play, or step through it at your own pace.
Concepts first, then the problem and every approach, step by step.
Space to play or pause · ← → to jump a step · click or drag the bar to seek
Solutions
Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the code in Java, Python, C++ and JavaScript.
| Approach | Time | Space |
|---|---|---|
| Brute force (sort, then walk back from the end) | O(n log n) | O(n) |
| Better (two passes) | O(n) | O(1) |
| Optimal (one pass with two trackers) | O(n) | O(1) |
1Brute force (sort, then walk back from the end)
O(n log n)Sorting dominates; the backward walk is at most n steps.O(n)The sorted copy holds n values (sorting in place would change the caller's array).Sort a copy of the array in ascending order. The maximum is now the last value. Walk backwards from the end and return the first value that is strictly smaller than the maximum, skipping over any repeats of it. If the walk reaches the front without finding one, every value equals the maximum and the answer is -1.
- Copy the array and sort the copy ascending.
- Let
maxbe the last value of the sorted copy. - For i from n - 2 down to 0: if
sorted[i] < max, returnsorted[i]. - If no value was smaller, return -1.
class Solution {
public int getSecondLargest(int[] arr) {
int[] sorted = arr.clone();
Arrays.sort(sorted);
int n = sorted.length;
int max = sorted[n - 1];
for (int i = n - 2; i >= 0; i--) {
if (sorted[i] < max) return sorted[i];
}
return -1;
}
}class Solution:
def getSecondLargest(self, arr: List[int]) -> int:
s = sorted(arr)
n = len(s)
mx = s[n - 1]
for i in range(n - 2, -1, -1):
if s[i] < mx:
return s[i]
return -1class Solution {
public:
int getSecondLargest(vector<int>& arr) {
vector<int> s(arr);
sort(s.begin(), s.end());
int n = s.size();
int mx = s[n - 1];
for (int i = n - 2; i >= 0; i--) {
if (s[i] < mx) return s[i];
}
return -1;
}
};function getSecondLargest(arr) {
const sorted = [...arr].sort((a, b) => a - b);
const n = sorted.length;
const max = sorted[n - 1];
for (let i = n - 2; i >= 0; i--) {
if (sorted[i] < max) return sorted[i];
}
return -1;
}2Better (two passes)
O(n)Two linear scans of the array.O(1)Only two variables.Sorting does far more work than needed: only the top two distinct values matter. The first pass finds the maximum. The second pass looks for the biggest value that is strictly below that maximum, ignoring every copy of the maximum itself. Since all values are positive, starting the answer at -1 means it stays -1 when nothing qualifies.
- Pass 1:
largest= the maximum of the array. - Pass 2:
second = -1; for every x withx < largestandx > second, setsecond = x. - Return
second.
class Solution {
public int getSecondLargest(int[] arr) {
int largest = -1;
for (int x : arr) {
if (x > largest) largest = x;
}
int second = -1;
for (int x : arr) {
if (x < largest && x > second) second = x;
}
return second;
}
}class Solution:
def getSecondLargest(self, arr: List[int]) -> int:
largest = -1
for x in arr:
if x > largest:
largest = x
second = -1
for x in arr:
if x < largest and x > second:
second = x
return secondclass Solution {
public:
int getSecondLargest(vector<int>& arr) {
int largest = -1;
for (int x : arr) {
if (x > largest) largest = x;
}
int second = -1;
for (int x : arr) {
if (x < largest && x > second) second = x;
}
return second;
}
};function getSecondLargest(arr) {
let largest = -1;
for (const x of arr) {
if (x > largest) largest = x;
}
let second = -1;
for (const x of arr) {
if (x < largest && x > second) second = x;
}
return second;
}3Optimal (one pass with two trackers)
O(n)One scan with a couple of comparisons per value.O(1)Only two variables.Keep largest and second while scanning once. A value bigger than largest is a new maximum, and the old maximum drops to second place. A value that is strictly between second and largest only improves second. A value equal to largest is a repeat of the maximum and changes nothing, which is exactly why repeats never become the answer.
- Set
largest = -1andsecond = -1(every value is at least 1). - For each x: if
x > largest, setsecond = largest, thenlargest = x. - Else if
x < largestandx > second, setsecond = x. - Return
second.
class Solution {
public int getSecondLargest(int[] arr) {
int largest = -1, second = -1;
for (int x : arr) {
if (x > largest) {
second = largest;
largest = x;
} else if (x < largest && x > second) {
second = x;
}
}
return second;
}
}class Solution:
def getSecondLargest(self, arr: List[int]) -> int:
largest, second = -1, -1
for x in arr:
if x > largest:
second = largest
largest = x
elif x < largest and x > second:
second = x
return secondclass Solution {
public:
int getSecondLargest(vector<int>& arr) {
int largest = -1, second = -1;
for (int x : arr) {
if (x > largest) {
second = largest;
largest = x;
} else if (x < largest && x > second) {
second = x;
}
}
return second;
}
};function getSecondLargest(arr) {
let largest = -1, second = -1;
for (const x of arr) {
if (x > largest) {
second = largest;
largest = x;
} else if (x < largest && x > second) {
second = x;
}
}
return second;
}Edge cases to test
- A single element: there is no second value, so return -1
- All values equal: return -1
- The maximum appears several times: its copies do not count as the second largest
- The maximum is the first element, so a one-pass scan never moves the old largest down
- The second largest comes before the maximum in the array
- Already sorted or reverse sorted input
Hints
Hint 1
The answer is not simply the second-to-last value after sorting: the maximum may appear more than once.
Hint 2
Find the maximum first. The answer is the largest value that is strictly smaller than it.
Hint 3
Can you keep both the largest and the second largest in one scan? When a new maximum shows up, the old maximum becomes the second largest.
FAQ
What is the best time complexity for Second Largest Element in an Array?
Optimal (one pass with two trackers) runs in O(n) time and O(1) extra space. One scan with a couple of comparisons per value.
Which pattern does Second Largest Element in an Array use?
It is a arrays & hashing problem that uses the sorting pattern. Other problems with the same pattern: Minimum Time Difference.
Is there a brute force solution for Second Largest Element in an Array?
Yes. Brute force (sort, then walk back from the end) takes O(n log n) time and O(n) space. Sort a copy of the array in ascending order.
Which edge cases should I test for Second Largest Element in an Array?
A single element: there is no second value, so return -1; All values equal: return -1; The maximum appears several times: its copies do not count as the second largest; The maximum is the first element, so a one-pass scan never moves the old largest down; The second largest comes before the maximum in the array; Already sorted or reverse sorted input.