The Deep Dive
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
- L4
- Asked in
- Meta
Problem
You're triaging a metrics export that maps each host to its request count, and several hosts can land on the exact same count. Given counts and a 1-based n, return the n-th highest distinct count, collapsing repeated counts to a single rank; return None when there aren't n distinct counts.
A specific position in the unsorted pile.
Example 1
Input:
counts = {"web1":10,"web2":30,"web3":20,"web4":30}, n = 1Output:
30
Example 2
Input:
counts = {"web1":10,"web2":30,"web3":20,"web4":30}, n = 2Output:
20
Worked solution and explanation
What this really is
Strip the host-metrics costume and this is a rank-over-distinct-values problem. The maximum is easy, and most people get a clean answer on n=1. What actually separates candidates is recognizing that two hosts sharing a count must collapse to one rank. The trap is reaching for sorted(counts.values(), reverse=True)[n-1]: the moment any value repeats, that repeat eats a rank, and your n-th element is a value you already counted, sitting one or more positions too high. The fix is one word, set, applied before you sort.
Walking it through
Step 1: Collapse to distinct counts
Pull the counts out of the dict and drop them into a set. Keys are noise here, and two hosts on the same count must become one entry, otherwise the rank math is wrong before you even sort.
Step 2: Sort distinct counts high to low
The n-th highest is position n in a descending list, so sort the distinct counts high to low. Sorting a deduplicated set, not the raw values, is the whole game.
Step 3: Index by rank, guard the edge
1-based n maps to index n-1, so the 1st highest sits at index 0. Before indexing, guard the boundary: if n is past the number of distinct counts, there is no n-th value, so return None rather than letting an IndexError escape.
The solution
def the_deep_dive(counts: dict[str, int], n: int):
distinct = sorted(set(counts.values()), reverse=True)
if n > len(distinct):
return None
return distinct[n - 1]set() folds the ties, sorted(..., reverse=True) ranks them, the guard handles n out of range.
Common follow-up questions
- How would you do this without sorting all the distinct counts? (Tests a heap or quickselect for O(k) average instead of a full sort.)
- What if you also needed every host whose count is the n-th highest? (Tests reverse-mapping a value back to the hosts that produced it.)
- How would the code change if n could be negative, meaning n-th lowest? (Tests adapting the index logic to rank from the bottom.)