Design A Leaderboard - Problem
Design a Leaderboard class for competitive gaming or sports applications.
Your leaderboard must support three key operations:
๐
๐
๐
Example: In an esports tournament, players earn points throughout multiple matches. You need to efficiently track rankings and calculate prize pools for top performers.
The leaderboard starts empty, and you're guaranteed that any player being reset was previously added.
Your leaderboard must support three key operations:
๐
addScore(playerId, score): Add points to a player's total score. If the player doesn't exist, create a new entry.๐
top(K): Return the sum of scores from the top K highest-scoring players.๐
reset(playerId): Remove a player from the leaderboard (reset their score to 0).Example: In an esports tournament, players earn points throughout multiple matches. You need to efficiently track rankings and calculate prize pools for top performers.
The leaderboard starts empty, and you're guaranteed that any player being reset was previously added.
Input & Output
example_1.py โ Basic Operations
$
Input:
leaderboard = Leaderboard()
leaderboard.addScore(1, 73) # Player 1: 73
leaderboard.addScore(2, 56) # Player 2: 56
leaderboard.addScore(3, 39) # Player 3: 39
leaderboard.top(2) # Query top 2
โบ
Output:
129
๐ก Note:
Top 2 players are Player 1 (73) and Player 2 (56). Sum = 73 + 56 = 129
example_2.py โ Reset Operation
$
Input:
leaderboard.reset(1) # Remove Player 1
leaderboard.addScore(2, 51) # Player 2: 56 + 51 = 107
leaderboard.top(3) # Query top 3
โบ
Output:
146
๐ก Note:
After reset, remaining players: Player 2 (107), Player 3 (39). Top 3 sum = 107 + 39 = 146
example_3.py โ Edge Case
$
Input:
new_board = Leaderboard()
new_board.addScore(1, 100)
new_board.top(5) # K > number of players
โบ
Output:
100
๐ก Note:
Only 1 player exists but K=5 requested. Return sum of all available players (just 100)
Constraints
- 1 โค playerId โค 105
- 1 โค score โค 105
- 1 โค K โค total number of players
- At most 1000 operations will be performed
- It is guaranteed that playerId exists before calling reset
Visualization
Tap to expand
Understanding the Visualization
1
Player Registration
New players are added to hash table when they first score points
2
Score Updates
During matches, player scores are updated instantly in O(1) time using hash table lookups
3
Live Rankings
When broadcast needs top K players, all scores are extracted and sorted once
4
Player Elimination
Disqualified players are removed from the leaderboard instantly
Key Takeaway
๐ฏ Key Insight: Use hash tables for lightning-fast score updates during live gameplay, accepting the cost of sorting only when rankings are actually needed for broadcasts or prize calculations.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code