Build a Deterministic Top-10 Leaderboard with Tie-Breaking
SQL & DataAuto-graded · 14 test casesLast updated
Tests your ability to produce a fixed-size ranked list when scores contain ties, using a stable secondary sort key.
You maintain a leaderboard table that tracks user scores. Your task is to return the top 10 users, but there's a catch: when multiple users share the same score, you must apply a consistent tie-breaking rule to ensure the output always contains exactly 10 entries (or fewer if the table has fewer than 10 rows).
Task
Given a list of score records, each containing a user_id (string) and a score (integer), return a list of exactly 10 user_id values representing the top 10 users.
Tie-breaking rule: When users have identical scores, rank them by user_id in ascending lexicographic order. This ensures the same input always produces the same output.
The returned list should be in leaderboard order: highest-scoring user first, with ties resolved by user_id.
Constraints
- 0 ≤ number of records ≤ 10,000
user_idis a non-empty stringscoreis an integer in the range [-1,000,000, 1,000,000]- Each record represents one leaderboard entry (there may be multiple records per
user_idif the input represents daily scores) - If there are fewer than 10 records, return all of them in sorted order
Examples
Example 1
Input: leaderboard_top_10([{'user_id': 'u1', 'score': 95}, {'user_id': 'u2', 'score': 92}, {'user_id': 'u3', 'score': 90}, {'user_id': 'u4', 'score': 90}, {'user_id': 'u5', 'score': 88}])
Output: ['u1', 'u2', 'u3', 'u4', 'u5']
Hints
Hint 1
Think about what happens if you use RANK() or DENSE_RANK() when positions 10 and 11 have the same score—how many rows would you get?
Hint 2
A deterministic result requires a total ordering. Use both score and user_id in your sort key.
Hint 3
In Python, sort by (-score, user_id) and slice the first 10. In SQL, use ROW_NUMBER() OVER (ORDER BY score DESC, user_id ASC) or simply ORDER BY ... LIMIT 10.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The core challenge is ensuring the output contains exactly 10 entries even when scores contain ties. If you were to use SQL window functions like RANK() or DENSE_RANK() and filter by rank ≤ 10, you could end up with 11 or more rows when multiple users tie at the boundary position.
The solution is to establish a total ordering that eliminates all ties:
- Primary sort: Order by score in descending order (highest first)
- Secondary sort: Break ties using
user_idin ascending lexicographic order - Limit: Take the first 10 entries from this fully ordered list
This approach guarantees:
- Exactly 10 rows (or fewer if the input has fewer than 10 records)
- Deterministic output: the same input always produces the same result
- Correct ranking: no lower-scoring user displaces a higher-scoring user
Why It Works
Since (score, user_id) forms a unique ordering key (assuming each record is distinct), every record gets a definite position in the sorted sequence. Slicing the first 10 positions always returns at most 10 entries, and the tie-breaker ensures the result is stable across runs.
In SQL terms, this is equivalent to:
SELECT user_id
FROM scores
ORDER BY score DESC, user_id ASC
LIMIT 10;
Or using ROW_NUMBER():
SELECT user_id
FROM (
SELECT user_id, ROW_NUMBER() OVER (ORDER BY score DESC, user_id ASC) AS rn
FROM scores
) ranked
WHERE rn <= 10;
Complexity
- Time: O(n log n) where n is the number of records, dominated by the sort
- Space: O(n) for the sorted copy of the input list
In practice, a database using LIMIT 10 can optimize this to O(n log 10) with a bounded heap.
Edge Cases
- Fewer than 10 records: Returns all records in sorted order
- Empty input: Returns an empty list
- All scores identical: Returns the 10 lexicographically smallest
user_idvalues - Lexicographic ordering: Since
user_idis a string, "u10" < "u2" lexicographically
Implementation
from typing import Dict, List
def leaderboard_top_10(records: List[Dict[str, object]]) -> List[str]:
# Sort by score descending, then by user_id ascending for deterministic tie-breaking
sorted_records = sorted(records, key=lambda r: (-r["score"], r["user_id"]))
# Take the first 10 entries
return [r["user_id"] for r in sorted_records[:10]]