Funcia
Tutorialarray

Second Largest Value

Memory limit
256 MB
Correctness time limit
10000 ms
Solvers
0
0

Given an integer array nums, return the second largest distinct value. Repeated values count once: in [5, 5, 3] the largest is 5 and the second largest is 3. At least two distinct values are guaranteed.

Examples

numsresult
[3, 9, 2, 7]7
[5, 5, 3]3
[-1, -4]-4

Example 1 — Largest 9, then 7.

Example 2 — 5 counts once, so the answer is 3.

Example 3 — -1 is the largest, -4 the second.

This is a tutorial problem: there are no performance tests, just return the correct value.

Function signature

solution(nums: int[]) → int

Constraints

  • 2≤2 \le nums.length ≤1,000\le 1{,}000
  • −109≤-10^9 \le nums[i] ≤109\le 10^9
  • nums contains at least two distinct values.

Expected complexity

Time
O(N)
Space
O(1)

Examples

numsExpected
[3,9,2,7]7
[5,5,3]3
[-1,-4]-4

Hint

Hint

Find the maximum first, then the largest value strictly smaller than first. (Or track first and second in one pass, ignoring values equal to first.) Don't start from 0: all values may be negative.

Time limits per language

LanguageEfficiency time limit
C (GCC, gnu17)200 msestimated
C++ (GCC, gnu++23)200 msderived
Python 3.131000 msderived
Java 251000 msderived
Kotlin 2.4 (JVM)1200 msestimated
C# 14 (.NET 10)1200 msestimated

Test groups

GroupWeightTestsVisibility
sample03inputs and outputs
correctness10014verdict only
Loading editor…
Log in to run or submit code.

No result yet. Run or submit your code.