JavaScriptEasyArrays10 min
Find the second-largest distinct value
Return the second-largest distinct integer, or null when fewer than two distinct values exist. All input is valid JSON satisfying the constraints; do not mutate the meaning of values through type coercion. Interviewers use this problem to assess track the two greatest distinct values.
Input
A JSON array of integers on stdin.
Output
Print one compact JSON value: an integer or null.
Constraints
0 <= array length <= 10000; integers between -1000000 and 1000000.
Example
Input
[5,2,5,4]
Output
4
Example 2 input
[4,4]
Output
null
Boundary case: Use null when a second distinct value is absent
Public test cases (2)
Input
[5,2,5,4]
Expected output
4
Input
[1,2]
Expected output
1
Hints (2)
- Do not count duplicate maxima
- Use null when a second distinct value is absent
Target complexity: time O(n) · space O(1)
