MediumHash TableDesignSortingHeap (Priority Queue)

Design a Leaderboard

LeetCode
1 approach, code in all languages

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.
You've got the patterns

Patterns get you through the screen. Shipping gets you hired.

FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.

750+ engineers trained · frontend, backend, AWS & AI

August 15 · 0d left
Enroll Now