The Numbered Chair
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
- Meta
Problem
Given a dict data mapping player names to scores, return the player name at the n-th position when sorted by score descending (tie-break by player name ascending). n is 1-based. If n exceeds the number of players, return None.
A standing list. Position n holds one entry.
Example
Input:
n = 2, data = {"a":1,"b":2,"c":100,"d":30}Output:
"d"
Worked solution and explanation
Why this problem exists in real interviews
This tests sorting dictionary entries by value and extracting a specific rank. It checks whether candidates understand key-value pair sorting, custom tie-breaking, and 1-based vs 0-based indexing.
Break down the requirements
Step 1: Sort entries by score descending, name ascending
Sort the (name, score) pairs by score descending, breaking ties by name ascending. The cleanest key is lambda kv: (-kv[1], kv[0]): negating the score sorts highest-first, while the name sorts alphabetically when scores tie.
Step 2: Return the name at position n
The position is 1-based, so the nth place corresponds to index n-1 in the sorted list. Guard for n exceeding the number of players by returning None.
The solution
def nth_highest_key(n, data):
if n < 1 or n > len(data):
return None
ordered = sorted(data.items(), key=lambda kv: (-kv[1], kv[0]))
return ordered[n - 1][0]Common follow-up questions
- What if two players are tied? (Tests how to define rank: dense ranking, standard competition ranking, or arbitrary.)
- How would you find the top 3 without sorting the entire dict? (Tests using a heap for O(k log 3) instead of O(k log k).)
- What if the scores dictionary is updated frequently? (Tests maintaining a sorted structure like a balanced BST or sorted list with bisect.)