The Second Summit

An easy Python interview practice problem on DataDriven. Write the Python and run it against test cases, with instant feedback.

Domain
Python
Difficulty
easy
Seniority
L3
Asked in
Gemini

Problem

Given a list of integers holding at least two different values, return the second-largest distinct value. You cannot use sort, sorted, min, or max.

Not the top of the mountain - just below it.

Example 1

Input:

nums = [3,1,4,1,5,9,2,6]

Output:

6

Example 2

Input:

nums = [8,8,5]

Output:

5

Worked solution and explanation

What this problem is really about

Strip the costume and this is a running top-two tracker, not a puzzle about finding two numbers. The real skill being probed: can you carry the largest and second-largest as you walk the list once, when the tools you'd normally reach for (sort, sorted, min, max) are all banned? Anyone can write the cascade when a new value beats first. The trap is the second branch: forget to check num != first and a repeat of the maximum sneaks into the second slot, so [5, 5, 3] hands back 5 instead of 3.


Break down the requirements

Step 1: Initialize first and second to negative infinity

Use float('-inf') as a sentinel that any real number will exceed, so the very first element always lands in first and an all-negative list like [-2, -8, -5] still works.

Step 2: Update on each element

If the current value exceeds first, cascade the old first down into second before overwriting first. If it only exceeds second and is distinct from first, update second. That distinctness check is the whole game.

Step 3: Return the second largest

After scanning every element, second holds the second-largest distinct value.


The solution

Two-variable tracking for the second distinct max
def second_largest_no_builtins(nums: list[int]) -> int:
    first = float('-inf')
    second = float('-inf')
    for num in nums:
        if num > first:
            second = first
            first = num
        elif num > second and num != first:
            second = num
    return second

Common follow-up questions