# The Deep Dive

> A specific position in the unsorted pile.

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

Domain: Python · Difficulty: easy · Seniority: L4

## Problem

Given a dict mapping string keys to integer values and integer n (1-based), return the n-th highest distinct value. Return None if there are fewer than n distinct values.

## Worked solution and explanation

### Why this problem exists in real interviews

This tests **sorting distinct values and selecting by rank**, a common leaderboard operation. It probes whether a candidate handles duplicate values correctly by deduplicating before ranking.

---

### Break down the requirements

#### Step 1: Extract distinct values from the dict

Use a set to collect unique values, ignoring duplicate counts across keys.

#### Step 2: Sort distinct values in descending order

The nth highest means position n in a descending sorted list.

#### Step 3: Return the value at index n-1

Return `None` if n exceeds the number of distinct values.

---

### The solution

**Distinct value extraction and ranked selection**

```python
def nth_highest(data: dict, n: int):
    unique_values = set()
    for val in data.values():
        unique_values.add(val)
    sorted_desc = sorted(unique_values, reverse=True)
    if n > len(sorted_desc):
        return None
    result = sorted_desc[n - 1]
    return result
```

> **Time and Space Complexity**
>
> **Time:** O(m log m) where m is the number of distinct values. Set construction is O(n) for n total entries.
> 
> **Space:** O(m) for the set and sorted list.

> **Interviewers Watch For**
>
> Whether you deduplicate before ranking. Without deduplication, `{'a': 5, 'b': 5, 'c': 3}` with n=2 would incorrectly return 5 instead of 3.

> **Common Pitfall**
>
> Off-by-one error: the 1st highest is at index 0, the 2nd at index 1, etc. Use `n - 1` for the index.

---

## Common follow-up questions

- How would you solve this without sorting? _(Tests using a heap or quickselect for O(n) average.)_
- What if you needed the key(s) associated with the nth highest value? _(Tests reverse-mapping from value back to keys.)_
- What if n could be negative (nth from the bottom)? _(Tests adapting to ascending sort or reversing the index logic.)_

## Related

- [All practice problems](https://datadriven.io/problems)
- [Mock interview mode](https://datadriven.io/interview/the_deep_dive)
- [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.