Problema
Return the second largest distinct value in the list. Repeated values count once.
Implement second_largest(numbers).
Input
numbers: A list of non-negative integers.
Output
Return the second largest distinct value, or -1 if it doesn't exist.
Restricciones
0 ≤ length ≤ 100,000; 0 ≤ each value ≤ 10⁹
Ejemplos
Entrada:
numbers = [4, 9, 7, 9]
Salida esperada:
expected = 7
Entrada:
std::vector<long long> numbers = {4, 9, 7, 9};
Salida esperada:
long long expected = 7;
Entrada:
long[] numbers = new long[] {4, 9, 7, 9};
Salida esperada:
long expected = 7;
Explicación
Distinct values are 9, 7, 4; the second largest is 7.
Entrada:
numbers = [5, 5]
Salida esperada:
expected = -1
Entrada:
std::vector<long long> numbers = {5, 5};
Salida esperada:
long long expected = -1;
Entrada:
long[] numbers = new long[] {5, 5};
Salida esperada:
long expected = -1;
Explicación
Only one distinct value exists, so the answer is -1.
Cómo abordarlo
Inténtalo primero por tu cuenta y luego abre las pistas una a una.
Pista 1
You need the largest and the next different value, not just the top two positions.
Pista 2
Track two distinct maxima as you scan, updating them when a new value fits above or between them.
Pista 3
If no second distinct value ever appears, return the special fallback value.
Complejidad esperada
O(n) time, O(1) extra space
Referencias
Este reto está adaptado para CodeUtility. Sigue el enunciado y las restricciones indicadas arriba.