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;
}

Was this page helpful?