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 HashMap + Sort on Demand Approach INPUT Operations: 1. Leaderboard() 2. addScore(1, 73) 3. addScore(2, 56) 4. top(2) HashMap Structure: scores HashMap playerId: 1 score: 73 playerId: 2 score: 56 Parameters: [[],[1,73],[2,56],[2]] ALGORITHM STEPS 1 Initialize Create empty HashMap 2 addScore() Update/add player score 3 top(K) Sort + sum top K scores 4 reset() Remove player from map top(2) Execution: Values: [73, 56] Sort DESC: [73, 56] Take top 2: 73 + 56 Sum = 73 + 56 = 129 FINAL RESULT Operation Results: Operation Result Leaderboard() null addScore(1,73) null addScore(2,56) null top(2) 129 Output: [129] OK - Sum of top 2 scores verified: 73 + 56 = 129 Key Insight: HashMap provides O(1) addScore and reset operations. For top(K), we sort values on demand with O(n log n) time. This "lazy" approach is efficient when top() is called infrequently compared to addScore(). Alternative: Use a heap for O(K log n) top() but more complex updates. TutorialsPoint - Design A Leaderboard | HashMap + Sort on Demand
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