Score Tracker with Ranking and Top-K Queries
Data Structure DesignAuto-graded · 18 test casesLast updated
Tests the ability to maintain ordered scores with efficient updates and rank lookups using augmented balanced search trees.
Build a score tracking system that processes a sequence of operations on player scores. The system must support three operations:
-
Update a player's score: Set a player's score to a new value. If the player is new, add them to the system. If they already exist, overwrite their previous score.
-
Query a player's rank: Return the player's current rank, where rank is defined as one plus the count of players who have a strictly higher score. If the player doesn't exist in the system, return
-1. -
Retrieve top performers: Return the IDs of up to
khighest-scoring players. Order the results by score descending; when multiple players share the same score, order them by ID ascending.
You'll implement a function that processes a list of operations and returns the corresponding outputs. Each operation that modifies state returns None, while queries return their results.
Input Format:
operations: A list of operation names:"update_score","get_rank", or"get_top_k"arguments: A parallel list where each element contains the parameters for the corresponding operation:"update_score":[player_id, score]- both integers"get_rank":[player_id]- single integer"get_top_k":[k]- single integer
Output Format:
Return a list containing one result per operation:
"update_score":None"get_rank": an integer rank (or-1if player not found)"get_top_k": a list of player IDs
Constraints:
- 1 ≤ number of operations ≤ 100,000
- Player IDs are unique positive integers
- Scores can be any integer (positive, negative, or zero)
- 0 ≤ k ≤ 100,000
- If
kexceeds the number of players, return all players in the correct order - If
k ≤ 0, return an empty list
Examples
Example 1
Input: score_tracker(['update_score', 'update_score', 'update_score', 'get_rank', 'get_top_k'], [[1, 50], [2, 80], [3, 80], [1], [2]])
Output: [None, None, None, 3, [2, 3]]
Example 2
Input: score_tracker(['update_score', 'get_rank', 'get_rank', 'get_top_k'], [[10, 100], [99], [10], [5]])
Output: [None, -1, 1, [10]]
Example 3
Input: score_tracker(['get_top_k', 'get_rank', 'update_score', 'get_top_k'], [[3], [7], [7, 20], [10]])
Output: [[], -1, None, [7]]
Hints
Hint 1
Think about what data structure lets you quickly find both 'how many elements are smaller than X' and 'give me the first k elements in order'.
Hint 2
A balanced binary search tree with size augmentation can answer order-statistic queries efficiently. Store players ordered by score (descending) and ID (ascending).
Hint 3
Use a tuple key like (-score, player_id) so Python's natural comparison gives you the correct leaderboard order. Maintain a hash map to track each player's current score for quick lookups.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The core challenge is maintaining a collection of scored players where we can efficiently determine both order (for ranking) and top-k elements. A hash map alone provides O(1) updates but O(N log N) sorting for queries. A simple sorted list requires O(N) insertion. The solution uses an augmented balanced binary search tree that combines fast updates with fast order queries.
Key Insight: Encoding Order in a Single Key
Store each player as a node keyed by (-score, player_id). Python compares tuples lexicographically, so this encoding naturally gives us:
- Higher scores come first (because we negate the score)
- Tied scores are broken by smaller player ID
An in-order traversal of this tree produces the leaderboard in the exact required order.
Tree Structure: Treap with Size Augmentation
A treap is a randomized balanced BST that's also a min-heap on random priorities. This keeps expected height at O(log N) with relatively simple code. Each node stores:
key: the(-score, player_id)tuplepriority: random value for heap balancingleft,right: childrensize: count of nodes in this subtree (enables order statistics)
Operations:
-
update_score(player_id, score):
- Look up the player's old score in the hash map
- If found, delete the old
(-old_score, player_id)key from the tree - Insert a new node with key
(-score, player_id) - Update the hash map
-
get_rank(player_id):
- Return -1 if player not found in hash map
- Walk down the tree comparing only the score component (index 0 of the key tuple)
- When we find a node with a strictly higher score (smaller negated value), count that node plus its entire left subtree
- The final count plus one is the rank
-
get_top_k(k):
- Perform an iterative in-order traversal
- Collect player IDs (index 1 of the key) until we have k results or exhaust the tree
Why It Works
- The BST invariant ensures in-order traversal produces sorted keys, which are already in leaderboard order
- Size augmentation lets us count "how many nodes have keys less than X" in O(log N) by summing left subtree sizes during descent
- The hash map tracks current scores in O(1), so we can quickly find a player's old key to delete it
- Treap rotations maintain both BST ordering and heap priorities, keeping expected height logarithmic
Complexity
-
Time:
update_score: O(log N) expected - one delete and one insert, each O(log N)get_rank: O(log N) expected - hash lookup O(1) plus tree descent O(log N)get_top_k: O(log N + k) - descend to leftmost node, then yield k elements
-
Space: O(N) for tree nodes and hash map
Where N is the number of unique players. With up to 100,000 players, expected tree height is around 17 levels.
Solution
import random
from typing import List
class _Node:
__slots__ = ("key", "priority", "left", "right", "size")
def __init__(self, key, priority):
self.key = key
self.priority = priority
self.left = None
self.right = None
self.size = 1
def _size(node):
return node.size if node is not None else 0
def _refresh(node):
if node is not None:
node.size = 1 + _size(node.left) + _size(node.right)
def _rotate_right(node):
child = node.left
node.left = child.right
child.right = node
_refresh(node)
_refresh(child)
return child
def _rotate_left(node):
child = node.right
node.right = child.left
child.left = node
_refresh(node)
_refresh(child)
return child
def _insert(root, node):
if root is None:
return node
if node.key < root.key:
root.left = _insert(root.left, node)
if root.left.priority < root.priority:
root = _rotate_right(root)
else:
root.right = _insert(root.right, node)
if root.right.priority < root.priority:
root = _rotate_left(root)
_refresh(root)
return root
def _merge(left, right):
if left is None:
return right
if right is None:
return left
if left.priority < right.priority:
left.right = _merge(left.right, right)
_refresh(left)
return left
right.left = _merge(left, right.left)
_refresh(right)
return right
def _delete(root, key):
if root is None:
return None
if key == root.key:
return _merge(root.left, root.right)
if key < root.key:
root.left = _delete(root.left, key)
else:
root.right = _delete(root.right, key)
_refresh(root)
return root
def _count_higher_scores(root, score_key):
count = 0
while root is not None:
if root.key[0] < score_key:
count += _size(root.left) + 1
root = root.right
else:
root = root.left
return count
def _first_k(root, k):
result = []
stack = []
current = root
while (current is not None or stack) and len(result) < k:
while current is not None:
stack.append(current)
current = current.left
current = stack.pop()
result.append(current.key[1])
current = current.right
return result
def score_tracker(operations, arguments):
root = None
scores = {}
rng = random.Random(918273)
output = []
for operation, args in zip(operations, arguments):
if operation == "update_score":
player_id, score = args
if player_id in scores:
old_score = scores[player_id]
root = _delete(root, (-old_score, player_id))
scores[player_id] = score
root = _insert(root, _Node((-score, player_id), rng.randrange(1 << 60)))
output.append(None)
elif operation == "get_rank":
player_id = args[0]
if player_id not in scores:
output.append(-1)
else:
output.append(_count_higher_scores(root, -scores[player_id]) + 1)
elif operation == "get_top_k":
output.append(_first_k(root, max(0, args[0])))
else:
raise ValueError("unknown operation")
return output