Real-Time Top K Players Leaderboard
Company: Tencent
Role: Software Engineer
Category: Software Engineering Fundamentals
Difficulty: medium
Interview Round: Other
We run a game server with up to 10,000 players whose scores update continuously. Design a data structure that supports efficiently registering players, updating their scores, and querying the top `k` players in real time.
The leaderboard is initialized with a fixed parameter `k`. `addScore` applies an incremental delta (creating the player with score `0` if missing), `setScore` overwrites the score, and `getScore` returns `-1` for unknown players.
`getTopK` returns the top `k` player IDs ordered by score descending, breaking ties by player ID ascending. If fewer than `k` players exist, return all of them.
Implement the following methods:
- `TopPlayersLeaderboard(k: int)`: Create an empty leaderboard that reports the top `k` players.
- `addScore(playerId: str, delta: int)`: Add `delta` to the player's score. Creates the player with score 0 if they do not exist.
- `setScore(playerId: str, score: int)`: Set the player's score to the given absolute value, creating the player if needed.
- `getScore(playerId: str) -> int`: Return the player's current score, or -1 if the player does not exist.
- `getTopK() -> List[str]`: Return up to k player IDs ordered by score descending, ties broken by playerId ascending.
Example 1:
```text
Input:
["TopPlayersLeaderboard", "addScore", "addScore", "setScore", "getTopK", "addScore", "getTopK", "getScore", "setScore", "getTopK", "addScore", "getScore"]
[[2], ["alice", 50], ["bob", 30], ["carol", 70], [], ["bob", 25], [], ["bob"], ["carol", 10], [], ["dave", -5], ["dave"]]
Output: [null, null, null, null, ["carol", "alice"], null, ["carol", "bob"], 55, null, ["bob", "alice"], null, -5]
Explanation:
lb = TopPlayersLeaderboard(2) # k = 2
lb.addScore("alice", 50) # new player: 0 + 50 = 50
lb.addScore("bob", 30) # new player: 0 + 30 = 30
lb.setScore("carol", 70) # new player set to 70
lb.getTopK() # -> ["carol", "alice"] (70, 50)
lb.addScore("bob", 25) # bob: 30 + 25 = 55
lb.getTopK() # -> ["carol", "bob"] (70, 55)
lb.getScore("bob") # -> 55
lb.setScore("carol", 10) # carol overwritten to 10
lb.getTopK() # -> ["bob", "alice"] (55, 50)
lb.addScore("dave", -5) # new player: 0 - 5 = -5
lb.getScore("dave") # -> -5
```
Example 2:
```text
Input:
["TopPlayersLeaderboard", "setScore", "setScore", "setScore", "getTopK", "getScore", "addScore", "getTopK"]
[[3], ["p1", 40], ["p2", 40], ["p3", 40], [], ["ghost"], ["p2", -10], []]
Output: [null, null, null, null, ["p1", "p2", "p3"], -1, null, ["p1", "p3", "p2"]]
Explanation:
lb = TopPlayersLeaderboard(3) # k = 3
lb.setScore("p1", 40) # scores: {p1=40}
lb.setScore("p2", 40) # scores: {p1=40, p2=40}
lb.setScore("p3", 40) # scores: {p1=40, p2=40, p3=40}
lb.getTopK() # -> ["p1", "p2", "p3"] (all tied, sorted by ID asc)
lb.getScore("ghost") # -> -1 (unknown player)
lb.addScore("p2", -10) # p2: 40 - 10 = 30
lb.getTopK() # -> ["p1", "p3", "p2"] (40, 40, 30)
```
```hint Two kinds of lookup
`getScore` looks a player up by ID, while `getTopK` needs players in ranked order. Ask whether one structure can serve both cheaply, and what has to stay in sync if you use more than one.
```
```hint Encoding the order
Score descending with ties by ID ascending is one combined sort order. Look for a single key whose natural ascending order matches it, and remember that an update must also get rid of the player's old position.
```
### Constraints & Assumptions
- Up to 10,000 distinct players.
- `1 <= k <= 10^4`
- `1 <= number of operations <= 10^5`
- Player IDs are non-empty strings of length up to `20`.
- `-10^9 <= delta, score <= 10^9`
- All scores fit within a signed 64-bit integer.
### Clarifying Questions to Ask
- Scores can go negative. How should a caller tell a real score of -1 apart from the -1 returned for an unknown player?
- Is ID order plain lexicographic string order, so that "p10" sorts before "p2"?
- Roughly how often is `getTopK` called compared with score updates?
- Must `getTopK` reflect every update immediately, or is a short delay acceptable?
### What a Strong Answer Covers
- How a score is read by player ID and how the ranked order is kept in step with every update
- A sort key or comparator that yields score descending with ties broken by ID ascending
- Removing the player's old ranked entry before inserting the new one, and the creation rules for `addScore` and `setScore`
- The cost of updates and `getTopK` for the chosen structure at 10,000 players, including any element shifting
- Edge cases: fewer than `k` players, negative scores, and the -1 sentinel for unknown players
### Follow-up Questions
- How would you return a given player's current rank efficiently?
- How would the design change for tens of millions of players spread across several servers?
- If `getTopK` is called far less often than scores change, what would you do differently?
- How would you keep the leaderboard consistent when many game threads update scores at once?
Overview: Design a game leaderboard that adds to a player's score, overwrites it, reads it back, and returns the top k players by score with ties broken by player ID. It tests choosing structures for lookups by ID and by rank, keeping them consistent on every update, and reasoning about update and query costs.