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

Sort by value, index by rank
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