Leaderboard implementation in Redis - Time & Space Complexity
When we build a leaderboard using Redis, we want to know how fast it can add scores and find rankings as more players join.
We ask: How does the work grow when the number of players grows?
Analyze the time complexity of the following code snippet.
ZADD leaderboard 1500 "player1"
ZADD leaderboard 2000 "player2"
ZADD leaderboard 1800 "player3"
ZRANK leaderboard "player2"
ZREVRANGE leaderboard 0 9 WITHSCORES
ZINCRBY leaderboard 100 "player1"
This code adds players with scores, finds a player's rank, lists top players, and updates a player's score.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Sorted set commands like ZADD, ZRANK, ZREVRANGE, and ZINCRBY that internally manage sorted data.
- How many times: Each command works on the sorted set of all players, which can be large.
As the number of players (n) grows, each operation takes more time but not equally.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 4 x log(10) ≈ 8 |
| 100 | About 4 x log(100) ≈ 18 |
| 1000 | About 4 x log(1000) ≈ 28 |
Pattern observation: The work grows slowly as the number of players grows, roughly increasing with the logarithm of n.
Time Complexity: O(log n)
This means that adding or finding a player's rank takes a little more time as the leaderboard grows, but it grows slowly and stays efficient.
[X] Wrong: "Adding a new player or updating a score takes the same time no matter how many players there are."
[OK] Correct: Actually, Redis uses a sorted data structure that needs to keep things in order, so it does a bit more work as the list grows, but this extra work grows slowly, not instantly.
Understanding how Redis handles leaderboards helps you explain how data structures affect speed, a useful skill when discussing real-world systems.
"What if we used a simple list instead of a sorted set for the leaderboard? How would the time complexity change?"