Editor

Live Leaderboard

#422 · Classes · Advanced · 160 XP · about 35 min

An online game shows a leaderboard of players ranked by total score. Build a Leaderboard class:

  • Leaderboard() starts with no players.
  • add_score(player, points) adds points to the player's total and returns the new total. A player who is not on the board joins it with a total of 0 first.
  • top(k) returns the best k players as a list of (player, total) tuples, highest total first. Players with the same total are listed in alphabetical order of name. If fewer than k players are on the board, it lists all of them.
  • reset(player) takes the player off the board, forgetting their total. Resetting a player who is not on the board does nothing.

Examples

lb = Leaderboard()
lb.add_score('mia', 50)     # returns 50
lb.add_score('leo', 80)     # returns 80
lb.add_score('ava', 50)     # returns 50
lb.add_score('mia', 40)     # returns 90
lb.top(2)                   # returns [('mia', 90), ('leo', 80)]
lb.reset('mia')
lb.top(3)                   # returns [('leo', 80), ('ava', 50)]

Constraints

  • Up to 100,000 calls; names are strings, points is a whole number from 1 to 1,000 and 1 <= k <= 100
  • Up to 30,000 players on the board at once, and top is called often: sorting every player on each call is too slow.

Fastest solvers

Leaderboard

First solves only, ranked by stars and then time.