Tutorialarray
Second Largest Value
- Memory limit
- 256 MB
- Correctness time limit
- 10000 ms
- Solvers
- 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
| nums | result |
|---|---|
[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
-
nums.length -
nums[i] numscontains at least two distinct values.
Expected complexity
- Time
- O(N)
- Space
- O(1)
Examples
| nums | Expected |
|---|---|
[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
| Language | Efficiency time limit | |
|---|---|---|
| C (GCC, gnu17) | 200 ms | estimated |
| C++ (GCC, gnu++23) | 200 ms | derived |
| Python 3.13 | 1000 ms | derived |
| Java 25 | 1000 ms | derived |
| Kotlin 2.4 (JVM) | 1200 ms | estimated |
| C# 14 (.NET 10) | 1200 ms | estimated |
Test groups
| Group | Weight | Tests | Visibility |
|---|---|---|---|
| sample | 0 | 3 | inputs and outputs |
| correctness | 100 | 14 | verdict only |