KatInterview

Build a Deterministic Top-10 Leaderboard with Tie-Breaking

SQL & DataAuto-graded · 14 test cases
MediumAuto-gradedSQL & Datarankingsortingtie-breaking

Last 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_id is a non-empty string
  • score is an integer in the range [-1,000,000, 1,000,000]
  • Each record represents one leaderboard entry (there may be multiple records per user_id if 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.