Coding problem · Easy · Basics
Second Largest Number
Easy Algorithms & data structures
Return the second-largest distinct value in nums. If all values are equal (or there's only one), return -1. Values are non-negative.
Example 1
Input: nums = [4,9,2,9,7] Output: 7 Explanation: 9 is the largest; the next distinct value is 7.
Example 2
Input: nums = [5,5] Output: -1
Hints
Hint 1
Track two variables, the largest and second largest, in one pass.
Hint 2
When you find a new largest, the old largest becomes the second largest. Skip values equal to the largest.
Write and run your solution
Loading the editor… (JavaScript is required to run code in your browser.)
Solution and explanation
Show the solution
Time O(n) · Space O(1)
Keep first and second. For each value: if it's bigger than first, shift first into second; else if it's between them (and not equal to first), update second.
Reference solution
function secondLargest(nums) {
let first = -1, second = -1;
for (const n of nums) {
if (n > first) { second = first; first = n; }
else if (n < first && n > second) second = n;
}
return second;
}
function secondLargest(nums: number[]): number {
let first = -1, second = -1;
for (const n of nums) {
if (n > first) { second = first; first = n; }
else if (n < first && n > second) second = n;
}
return second;
}
def second_largest(nums: list[int]) -> int:
first = second = -1
for n in nums:
if n > first:
first, second = n, first
elif second < n < first:
second = n
return second
<?php
function secondLargest(array $nums): int
{
$first = $second = -1;
foreach ($nums as $n) {
if ($n > $first) {
$second = $first;
$first = $n;
} elseif ($n < $first && $n > $second) {
$second = $n;
}
}
return $second;
}
class Solution {
public int secondLargest(int[] nums) {
int first = -1, second = -1;
for (int n : nums) {
if (n > first) { second = first; first = n; }
else if (n < first && n > second) second = n;
}
return second;
}
}
More Basics problems
- Reverse a String · Easy
- Count the Vowels · Easy
- Capitalize Each Word · Easy
- Longest Word in a Sentence · Easy
- Run-Length Encoding · Easy
- Is It a Pangram? · Easy