MediumHash TableDesignSortingHeap (Priority Queue)

Design a Leaderboard

1 approach, code in every language

Problem description

Design a leaderboard for a game where every player has a running total score. Players are identified by an integer id, and their score accumulates as they play.

Implement a Leaderboard class that supports three operations:

addScore(playerId, score): Add the given score to the player's cumulative total. If the player is not yet on the board, register them with a starting score of 0 and then add the given score.

top(K): Return the sum of the K highest cumulative scores currently on the board.

reset(playerId): Reset the given player's cumulative score back to 0. It is guaranteed that the player exists when reset is called.

Initially the leaderboard is empty.

Example 1

Input: Leaderboard(); addScore(1, 73); addScore(2, 56); addScore(3, 39); addScore(4, 51); addScore(5, 4); top(1); reset(1); reset(2); addScore(2, 51); top(3);

Output: 73, 141

After the five addScore calls the totals are {1:73, 2:56, 3:39, 4:51, 5:4}. top(1) returns the single largest total, 73. After resetting players 1 and 2 to 0 and adding 51 to player 2, the totals are {1:0, 2:51, 3:39, 4:51, 5:4}. top(3) sums the three largest totals: 51 + 51 + 39 = 141.

Example 2

Input: Leaderboard(); addScore(1, 10); addScore(1, 20); top(1); reset(1); top(1);

Output: 30, 0

Two addScore calls on player 1 accumulate to 30, so top(1) is 30. After reset(1) the player's total is 0, so top(1) sums the single largest total, which is now 0.

Constraints

  • 1 <= playerId, K <= 10^4
  • It is guaranteed that K is less than or equal to the current number of players.
  • 1 <= score <= 100
  • At most 10^4 function calls will be made across addScore, top, and reset.

After the pattern

Now solve one you haven't seen.

Reading a pattern isn't the same as using it. The practice set has 1,194 original problems on the same techniques, each graded in your browser.

1,194 problems · 15,062 graded tests · free