Skip to content

System Design

Leaderboard / Ranking

O(n log n) time to produce a full ranking (n = number of players), because of the sort · O(n) space to hold the scores. Real large-scale leaderboards use smarter data structures, like sorted sets, to update a single score in O(log n) time — instead of re-sorting everything.

The idea, in plain English

A leaderboard is a scoreboard. It tracks everyone's score and always shows them ranked from highest to lowest. The tricky part is ties. You need a consistent tie-breaker — here, alphabetical order by name — so the ranking never wobbles. Whenever someone's score changes, you must recompute the ranking.

How it works

  1. 1Keep a running score for every player in a lookup table: name maps to total score.
  2. 2To show the leaderboard, sort all the names. Sort by score first, highest to lowest. Break ties by name, alphabetically.
  3. 3When a player earns more points, add them to that player's running score. Then re-sort to get the fresh ranking.

When you'd use it

Use this for any 'top players,' 'most active users,' or 'trending posts' feature — anywhere you need to show things ranked by a number that keeps changing.

Common beginner mistakes

  • Sorting only by score and leaving ties in a random, unstable order. Two players with the same score should always land in the same order — otherwise the leaderboard looks like it's glitching.
  • Recomputing everyone's rank by re-fetching all the data from scratch every time someone scores a point. Instead, just update the one player who changed.

Try it — edit and run

Click the code to edit · press ⌘/Ctrl+↵ to run

Editable code. Tab and Shift+Tab indent. Press Escape, then Tab, to move focus out of the editor.

Expected output — hit Run to try it
Leaderboard:
1. bob - 80
2. carol - 80
3. dave - 65
4. alice - 50
After alice scores 40 more points:
1. alice - 90
2. bob - 80
3. carol - 80
4. dave - 65

Not sure this is the right topic? See the learning paths → or where this leads →