Arrays and Hashing Array basics

48. Second Largest Element

Easy

You are given an array of non-negative integers nums. Return its second largest value: the largest value in nums that is strictly smaller than the maximum.

Values are compared, not positions. If the maximum appears more than once, its other copies are not the second largest. If every element equals the maximum, no value is smaller, so return -1.

Example 1

Input: nums = [4, 9, 2, 9, 7]

Output: 7

Explanation: The maximum is 9, and it appears twice. The values below it are 4, 2 and 7, and the largest of those is 7.

Example 2

Input: nums = [6, 6, 6]

Output: -1

Explanation: Every element is 6, so no value is smaller than the maximum.

Example 3

Input: nums = [10, 0, 10]

Output: 0

Explanation: The only value below 10 is 0, so the answer is 0. Zero is a real answer here, and it is different from -1.

Check your understanding

Work out the answer for this input before you write any code.

nums = [9, 4, 9, 4, 1]

Constraints

  • 1 ≤ nums.length ≤ 105
  • 0 ≤ nums[i] ≤ 109

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.