# The Runner-Up

> Not the winner. The one just behind it.

Canonical URL: <https://datadriven.io/problems/the_runner_up>

Domain: Python · Difficulty: easy · Seniority: L5

## Problem

Return the second-largest distinct value in the input list of integers. If the list has fewer than two distinct values, return None.

## Worked solution and explanation

### Why this problem exists in real interviews

This tests the ability to **track two distinct maximums** in a single pass. It checks whether candidates can handle the 'second largest' requirement without sorting, which would be O(n log n) when O(n) suffices.

---

### Break down the requirements

#### Step 1: Initialize two tracking variables

Set `first` and `second` to negative infinity. These track the largest and second-largest distinct values.

#### Step 2: Update on each element

If the element exceeds `first`, shift `first` down to `second` and update `first`. If it is between `first` and `second` (and distinct from `first`), update `second`.

#### Step 3: Return second or None

If `second` was never updated from its initial value, fewer than 2 distinct values exist.

---

### The solution

**Single-pass two-max tracking**

```python
def second_largest(nums):
    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
    if second == float('-inf'):
        return None
    return second
```

> **Time and Space Complexity**
>
> **Time:** O(n) with a single pass.
> 
> **Space:** O(1). Two tracking variables.

> **Interviewers Watch For**
>
> Do you handle duplicates of the largest value? If the list is `[5, 5, 5]`, the second largest does not exist. The `num != first` condition prevents duplicates from being treated as the second value.

> **Common Pitfall**
>
> Using a set to deduplicate and then sorting. This works but is O(n log n) when the single-pass approach is O(n).

---

## Common follow-up questions

- How would you find the kth largest without sorting? _(Tests the quickselect algorithm for O(n) average-case kth element.)_
- What if you needed both the largest and the index of the second largest? _(Tests tracking indices alongside values.)_
- What if the list were a stream? _(Tests maintaining a heap of size 2 as elements arrive.)_

## Related

- [All practice problems](https://datadriven.io/problems)
- [Mock interview mode](https://datadriven.io/interview/the_runner_up)
- [Python Interview Questions](https://datadriven.io/python-interview-questions)
- [Data Engineering Interview Prep Guide](https://datadriven.io/data-engineer-interview-prep)
- [Daily Challenge](https://datadriven.io/daily)

---

Source: DataDriven (https://datadriven.io). 100% free data engineering interview prep. Live code execution against Postgres 16, Python 3.11, and Spark sandboxes. No paywall, no premium tier, no signup gate.