Drill

ProblemsPython › data

The second highest number

easydataPython

A leaderboard shows only the top name, but the report also wants the runner-up.

second_largest(values: list<int>) → int

Solve it in the editor →

Where you start

def second_largest(values: list[int]) -> int:
    

Worked examples

CallResult
second_largest([3, 1, 2])2
second_largest([10, 10, 9])9
second_largest([4, 1, 4, 2, 3])3
second_largest([5])-1

Hint

Walk once keeping the two best so far, and ignore a value equal to the current best.

Reference solution in Python
def second_largest(values: list[int]) -> int:
    found = False
    second = 0
    best = 0
    started = False
    for v in values:
        if not started:
            best = v
            started = True
            continue
        if v > best:
            second = best
            found = True
            best = v
        elif v < best:
            if not found or v > second:
                second = v
                found = True
    return second if found else -1

The same problem in another language

More data problems in Python