Design a leaderboard
December 28, 2022
array-and-hashmap designProblem URL: Design a leaderboard
We will use a hashmap to store the score of each player. We will store the score of each player and we can look up in constant time.
class Leaderboard:
def __init__(self):
self.store = collections.Counter()
def addScore(self, playerId: int, score: int) -> None:
self.store[playerId] += score
def top(self, K: int) -> int:
return sum(v for i,v in self.store.most_common(K))
def reset(self, playerId: int) -> None:
self.store[playerId] = 0
# Your Leaderboard object will be instantiated and called as such:
# obj = Leaderboard()
# obj.addScore(playerId,score)
# param_2 = obj.top(K)
# obj.reset(playerId)
Time complexity: O(1)
for addScore
and reset
and O(nlog(n))
for top
Space complexity: O(n)