Design a Leaderboard
Medium
Topics
Design a leaderboard that tracks player scores.
Leaderboard() starts empty. addScore(playerId, score) adds score to that player’s total, registering the player if they are new. top(K) returns the sum of the K highest scores. reset(playerId) sets that player’s score to 0 and removes them from the board.
Example 1
addScore adds to a player’s running total rather than replacing it, and registers the player if they are new. reset takes a player off the board entirely, so they are not counted as a zero. top(K) returns the sum of the K highest totals, not the players holding them.Input: operations = ["Leaderboard","addScore","addScore","addScore","addScore","addScore","top","reset","reset","addScore","top"], values = [[],[1,73],[2,56],[3,39],[4,51],[5,4],[1],[1],[2],[2,51],[3]] Output: [null,null,null,null,null,null,73,null,null,null,141] Explanation: After the resets and the new score the board holds 51, 39, 51 and 4, whose top three sum to 141.
Constraints
- 1 <= playerId, K <= 10000
- It is guaranteed that K is less than or equal to the current number of players.
- 1 <= score <= 100
- At most 1000 calls in total.
Editorial — intuition, approach, complexity and pitfalls
Intuition
The three operations pull in different directions. addScore and reset want a map keyed by player; top wants the scores ordered. Keeping both perfectly in step on every call is more machinery than the stated limits need.
With at most 1000 calls, the honest reading is that addScore and reset should be O(1) on a map, and top can afford to look at the scores it needs when asked. Note the detail that makes addScore cumulative: it adds to the existing total rather than replacing it.
Approach
- Keep a map from player id to their running total.
- On
addScore, add to the entry, creating it at 0 first if the player is new. - On
reset, remove the player from the map entirely — a player with score 0 is off the board, not on it with a zero. - On
top(K), take the scores, pick theKlargest and sum them.
Walkthrough
addScore(1,73) {1:73}
addScore(2,56) {1:73, 2:56}
top(1) largest score -> 73
reset(1) {2:56}
reset(2) {}
addScore(2,51) {2:51}Complexity
- Time — O(1) for addScore and reset, O(n log n) for top: the first two are single map operations; top orders the n current scores. Selecting the K largest instead of fully ordering them brings top down to O(n log K).
- Space — O(n): one entry per registered player.
Common Pitfalls
addScoreaccumulates — overwriting the previous total is the most common misreading.- A reset player must leave the board rather than sit on it with a score of 0, or they would be counted among the top K.
Full Solution — all languages
class Leaderboard:
def __init__(self):
self.scores = {}
def addScore(self, playerId, score):
self.scores[playerId] = self.scores.get(playerId, 0) + score
def top(self, K):
return sum(sorted(self.scores.values(), reverse=True)[:K])
def reset(self, playerId):
self.scores.pop(playerId, None)import java.util.*;
class Leaderboard {
private final Map<Integer, Integer> scores = new HashMap<>();
public Leaderboard() {
}
public void addScore(int playerId, int score) {
scores.merge(playerId, score, Integer::sum);
}
public int top(int K) {
List<Integer> all = new ArrayList<>(scores.values());
all.sort(Comparator.reverseOrder());
long total = 0;
for (int i = 0; i < Math.min(K, all.size()); i++) total += all.get(i);
return (int) total;
}
public void reset(int playerId) {
scores.remove(playerId);
}
}#include <bits/stdc++.h>
using namespace std;
class Leaderboard {
public: Leaderboard() {
}
void addScore(int playerId, int score) {
scores[playerId] += score;
}
int top(int K) {
vector<int> all;
for (auto& kv : scores) all.push_back(kv.second);
sort(all.rbegin(), all.rend());
long long total = 0;
for (int i = 0; i < min((int)all.size(), K); i++) total += all[i];
return (int)total;
}
void reset(int playerId) {
scores.erase(playerId);
}
private: unordered_map<int, int> scores;
};class Leaderboard {
constructor() {
this.scores = new Map();
}
addScore(playerId, score) {
this.scores.set(playerId, (this.scores.get(playerId) || 0) + score);
}
top(K) {
const all = [...this.scores.values()].sort((a, b) => b - a);
let total = 0;
for (let i = 0; i < Math.min(K, all.length); i++) total += all[i];
return total;
}
reset(playerId) {
this.scores.delete(playerId);
}
}