Design A Leaderboard - Problem

Design a Leaderboard class with three main functions:

  • addScore(playerId, score): Update the leaderboard by adding the given score to the player's existing score. If the player doesn't exist, add them with the given score.
  • top(K): Return the sum of scores of the top K players on the leaderboard.
  • reset(playerId): Reset the player's score to 0 (remove them from the leaderboard). The player is guaranteed to exist.

Initially, the leaderboard is empty.

Input & Output

Example 1 — Basic Operations
$ Input: operations = ["Leaderboard","addScore","addScore","top"], parameters = [[],[1,73],[2,56],[2]]
Output: [129]
💡 Note: Create leaderboard, add player 1 with 73 points, add player 2 with 56 points, then get top 2 sum: 73 + 56 = 129
Example 2 — Multiple Updates
$ Input: operations = ["Leaderboard","addScore","addScore","addScore","top"], parameters = [[],[1,73],[2,56],[1,39],[3]]
Output: [168]
💡 Note: Player 1 gets 73+39=112 total, player 2 has 56. Top 3 sum: 112 + 56 = 168
Example 3 — Reset Operation
$ Input: operations = ["Leaderboard","addScore","addScore","reset","top"], parameters = [[],[1,73],[2,56],[1],[1]]
Output: [56]
💡 Note: After adding scores and resetting player 1, only player 2 remains with 56 points

Constraints

  • 1 ≤ playerId ≤ 104
  • 1 ≤ K ≤ total number of players
  • 1 ≤ score ≤ 100
  • At most 1000 calls will be made to addScore, top, and reset

Visualization

Tap to expand
Design A Leaderboard: System OverviewOperationsaddScore(1, 73)addScore(2, 56)top(2)HashMap StoragePlayer 1: 73Player 2: 56O(1) UpdatesQuery ResultSort: [73, 56]Sum top 2= 129addScoreO(1) timetop(K)O(n log n) timeresetO(1) timeKey Trade-off: Fast updates vs. query-time sortingSpace: O(n) for storing all player scores
Understanding the Visualization
1
Input Operations
Sequence of addScore, top, and reset commands
2
Data Management
HashMap stores player scores efficiently
3
Query Results
top(K) returns sum of highest K scores
Key Takeaway
🎯 Key Insight: Use HashMap for constant-time updates and sort only when querying top K scores
Asked in
Amazon 15 Google 12 Microsoft 8
28.5K Views
Medium Frequency
~25 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen