Live Scoreboard With Rank and Top-K Lookups

Medium · Coding & Algorithms · Software Engineer · Technical Screen

Problem Statement

Build an in-memory Leaderboard service that maintains one live integer score per competitor and answers rank and top-player queries as scores change over time.

Support three methods on the scoreboard:

  1. update_score(user_id: int, score: int) -> None — Sets the active score for user_id to score. Register user_id if they have not appeared before; otherwise overwrite their previous score (scores are replaced, not added).
  2. get_rank(user_id: int) -> int — Computes user_id's 1-based competition rank, defined as 1 plus the count of registered competitors whose current score is strictly greater than user_id's score. Competitors with identical scores therefore share the same rank, and if user_id has never been registered, return -1.
  3. get_top_k(k: int) -> List[int] — Produces up to k competitor IDs ordered from highest score to lowest score. Break equal-score ties by smaller user_id first. When fewer than k competitors exist on the board, return all registered competitors in that order (or [] when k == 0 or the board is empty).

For evaluation, implement dynamic_leaderboard(operations: List[str], arguments: List[List[int]]) -> List[object], which starts from an empty Leaderboard, runs each (operation, args) pair in sequence, and collects the return values (None for "update_score").

Examples

Example 1

Input:
  operations = ["update_score", "update_score", "update_score", "get_rank", "get_rank", "get_top_k"]
  arguments  = [[101, 40], [105, 95], [102, 95], [101], [105], [2]]
Output:
  [None, None, None, 3, 1, [102, 105]]

Explanation: Competitors 105 and 102 both hold score 95, while 101 holds 40. Two competitors strictly beat 40, placing 101 at rank 1 + 2 = 3, whereas zero competitors strictly beat 95, placing 105 at rank 1. Asking for the top 2 returns [102, 105] because 102 < 105 breaks the tie at 95.

Example 2

Input:
  operations = ["update_score", "update_score", "get_rank", "update_score", "get_rank", "get_top_k"]
  arguments  = [[4, 60], [8, 75], [404], [4, 90], [8], [5]]
Output:
  [None, None, -1, None, 2, [4, 8]]

Explanation: Competitor 404 has never been recorded, so get_rank(404) yields -1. Updating competitor 4 from 60 to 90 replaces their old score and pushes competitor 8 (75) down to rank 2. Requesting k = 5 when only two competitors exist returns both in order: [4, 8].

Example 3

Input:
  operations = ["get_top_k", "get_rank", "update_score", "get_rank", "get_top_k"]
  arguments  = [[4], [25], [25, -15], [25], [1]]
Output:
  [[], -1, None, 1, [25]]

Explanation: Before any score is recorded, get_top_k(4) returns [] and get_rank(25) returns -1. Once competitor 25 records -15, they are the sole player on the board with rank 1 and top-1 list [25].

Constraints

  • user_id values are unique integers per competitor; score can be negative, zero, or positive.
  • At most 100,000 distinct user_ids and operations are processed.
  • k >= 0 for all get_top_k(k) queries.
  • Both update_score and get_rank must run faster than O(N) per call, where N is the number of registered competitors.

Step-by-step walkthrough

  1. Restate the problem

    We need an in-memory Leaderboard class that tracks one active integer score per user_id and serves three operations cleanly across up to N = 100,000 competitors:

    • update_score(user_id, score): Registers user_id if new, or overwrites their previous score with score (non-cumulative).
    • get_rank(user_id): Computes 1 + (count of competitors holding a strictly greater score). Tied competitors share the same rank and cause trailing ranks to skip (for instance, scores 95, 95, 40 receive ranks 1, 1, 3). Querying an unregistered user_id returns -1.
    • get_top_k(k): Produces up to k competitor IDs ordered from highest score to lowest score, breaking equal-score ties by smaller user_id first. When fewer than k competitors exist, return all of them; when k == 0 or the board is empty, return [].

    The harness calls dynamic_leaderboard(operations, arguments) and records each return value (None for update_score), requiring both update_score and get_rank to run faster than O(N).

  2. Why a plain dict or sorted list hits an O(N) wall

    Consider the two most obvious standard-library containers:

    • Plain dictionary (user_id -> score): update_score runs in O(1), yet every get_rank must scan all N entries (O(N)) and get_top_k must sort or heapify the entire table (O(N log N) or O(N + k log N)). Over 100,000 queries on 100,000 competitors, O(N) per rank call reaches 10^10 comparisons.
    • Sorted Python list (bisect): Binary search answers get_rank in O(log N) and slicing reads the top k in O(k), yet every update_score deletes and re-inserts inside a contiguous array, shifting up to N items in O(N) time.

    Achieving O(log N) for both update_score and get_rank calls for a height-balanced search tree where each node tracks how many nodes reside in its subtree.

  3. Key idea: composite key (-score, user_id) in an augmented treap

    Combining two structural ideas handles ordering, tie-breaking, and self-balancing cleanly:

    1. Composite key (-score, user_id): Negating score makes larger scores compare smaller, and placing user_id second orders ties by ascending ID. Because user_id is unique per competitor, every active node in the tree has a strictly unique key, even when thousands of players share the same score!
    2. Size-augmented Treap (Tree + Heap): Python's standard library lacks a self-balancing search tree, and inserting monotonic scores into an unbalanced BST degenerates into an O(N) chain. A treap stays balanced in ~40 lines by assigning each node a random float priority:
      • key obeys binary-search-tree order (left < node < right).
      • priority obeys max-heap order (parent priority > child priority).
      • size maintains 1 + size(left) + size(right), letting us count an entire subtree in O(1) time without descending into it.
    Example 1 players: (101, 40), (105, 95), (102, 95)
    Keys in BST order: (-95, 102) < (-95, 105) < (-40, 101)
    
    Sample treap (suppose random priorities place (-95, 105) at the root):
    
                 [key=(-95, 105), score=95, size=3]
                  /                              \
      [key=(-95, 102), score=95, size=1]    [key=(-40, 101), score=40, size=1]
    
    In-order walk (left -> node -> right): user 102, user 105, user 101
    
  4. Code the treap node and split / merge primitives

    Rather than writing left/right tree rotations by hand, a treap relies on two compact recursive operations:

    • split(node, pivot_key) partitions one treap into (smaller, larger), where smaller contains all keys < pivot_key and larger contains all keys >= pivot_key.
    • merge(left, right) joins two treaps whenever every key in left is strictly smaller than every key in right: whichever root holds the larger priority becomes the combined root, and we recursively merge the remaining child subtree.

    Whenever a child pointer updates, refresh_size(node) recomputes node.size on the return path.

    split(root, pivot_key):                  merge(left, right) when left.prio > right.prio:
            [node]                                       [left]
            /    \    (if node.key < pivot)              /    \
           L      R   ====================►             L    merge(left.right, right)
         kept   split(R, pivot) -> (SR, larger)
    
    from typing import Any, Dict, List, Optional, Set, Tuple
    import random
    
    
    class TreapNode:
        def __init__(self, user_id: int, score: int, priority: float):
            self.user_id = user_id
            self.score = score
            # Composite BST key (-score, user_id): smaller tuple = higher score, or smaller user_id on ties.
            self.key: Tuple[int, int] = (-score, user_id)
            # Random max-heap priority keeps expected tree height O(log N) without manual rotations.
            self.priority = priority
            # Subtree node count (1 + left size + right size) for O(log N) rank counting.
            self.size = 1
            self.left: Optional["TreapNode"] = None
            self.right: Optional["TreapNode"] = None
    
    
    def subtree_size(node: Optional[TreapNode]) -> int:
        return node.size if node is not None else 0
    
    
    def refresh_size(node: TreapNode) -> None:
        # Recompute subtree count whenever `node.left` or `node.right` changes.
        node.size = 1 + subtree_size(node.left) + subtree_size(node.right)
    
    
    def split(
        node: Optional[TreapNode],
        pivot_key: Tuple[int, int],
    ) -> Tuple[Optional[TreapNode], Optional[TreapNode]]:
        """Partition `node` into two treaps: (keys < pivot_key, keys >= pivot_key)."""
        if node is None:
            return None, None
    
        if node.key < pivot_key:
            # `node` and its entire left subtree belong to the `< pivot_key` side.
            smaller_right, larger = split(node.right, pivot_key)
            node.right = smaller_right
            refresh_size(node)
            return node, larger
    
        # `node` and its entire right subtree belong to the `>= pivot_key` side.
        smaller, larger_left = split(node.left, pivot_key)
        node.left = larger_left
        refresh_size(node)
        return smaller, node
    
    
    def merge(
        left: Optional[TreapNode],
        right: Optional[TreapNode],
    ) -> Optional[TreapNode]:
        """Combine two treaps when every key in `left` is strictly smaller than every key in `right`."""
        if left is None:
            return right
        if right is None:
            return left
    
        # Keep the higher-priority root on top to preserve the max-heap invariant.
        if left.priority > right.priority:
            left.right = merge(left.right, right)
            refresh_size(left)
            return left
    
        right.left = merge(left, right.left)
        refresh_size(right)
        return right
    
  5. Code erase and update_score

    To erase an existing target_key, search down the BST until node.key == target_key, then splice node out via merge(node.left, node.right) (valid because every key in node.left precedes every key in node.right).

    Inside Leaderboard: - self.scores (user_id -> current score) checks in O(1) whether user_id is already present and retrieves old_score so we can form old_key = (-old_score, user_id) and erase their prior node. - To insert (user_id, score), we split at new_node.key and merge the three ordered parts smaller, new_node, and larger.

    def erase(
        node: Optional[TreapNode],
        target_key: Tuple[int, int],
    ) -> Optional[TreapNode]:
        """Delete `target_key` from the treap and return the updated subtree root."""
        if node is None:
            return None
        if node.key == target_key:
            # Splice `node` out by merging its two ordered subtrees directly.
            return merge(node.left, node.right)
        if target_key < node.key:
            node.left = erase(node.left, target_key)
        else:
            node.right = erase(node.right, target_key)
        refresh_size(node)
        return node
    
  6. Code get_rank: count strictly higher scores in O(log N)

    Inside get_rank(user_id), we count how many registered competitors satisfy score > target_score. Watch the subtle detail here: count_higher compares node.score > target_score, NOT the composite tuple node.key! (Comparing full tuples would treat (95, user 102) as beating (95, user 105), breaking shared ranks on ties.)

    At each step down from the root: - When node.score > target_score: Every node inside node.left has a smaller key ((-left.score, left.id) < (-node.score, node.id)), ensuring left.score >= node.score > target_score. Thus node and all of node.left strictly beat target_score! Add 1 + subtree_size(node.left) in O(1) and descend into node.right to check for any remaining higher scores. - Otherwise (node.score <= target_score): Every node inside node.right satisfies right.score <= node.score <= target_score, so neither node nor node.right can beat target_score. Descend into node.left without adding anything.

    Counting scores > 40 when visiting node (score=95):
            [score=95]       95 > 40!
             /      \        1. All of `left` has score >= 95 > 40 -> add 1 + size(left)
         [left]    [right]   2. Move into `right` to check for more scores > 40
    
    def count_higher(node: Optional[TreapNode], target_score: int) -> int:
        """Count how many users in the treap have `score > target_score`."""
        higher_count = 0
        while node is not None:
            # Compare raw scores (NOT full keys) so tied users never count as beating one another.
            if node.score > target_score:
                # Every node in `node.left` has key < node.key, so left.score >= node.score > target_score.
                higher_count += 1 + subtree_size(node.left)
                node = node.right
            else:
                # Here node.score <= target_score, and all of `node.right` has score <= node.score.
                node = node.left
        return higher_count
    
  7. Code get_top_k and the judge driver

    Because (-score, user_id) already matches get_top_k's exact sort order, an in-order walk (left -> node -> right) visits competitors from first place downward. Driving that walk with an explicit stack stops as soon as len(top_ids) == k, running in O(k + log N) expected time rather than visiting all N nodes.

    def first_k_ids(root: Optional[TreapNode], k: int) -> List[int]:
        """Collect the first `k` user_ids via an iterative in-order walk that stops early."""
        top_ids: List[int] = []
        stack: List[TreapNode] = []
        node = root
    
        while len(top_ids) < k and (node is not None or stack):
            while node is not None:
                stack.append(node)
                node = node.left
            visited = stack.pop()
            top_ids.append(visited.user_id)
            node = visited.right
    
        return top_ids
    
  8. Walk through Example 1

    Let's trace Example 1 step by step:

    1. update_score(101, 40) -> scores = {101: 40},            sorted keys: [(-40, 101)]
    2. update_score(105, 95) -> scores = {101: 40, 105: 95},   sorted keys: [(-95, 105), (-40, 101)]
    3. update_score(102, 95) -> scores = {..., 102: 95},       sorted keys: [(-95, 102), (-95, 105), (-40, 101)]
    4. get_rank(101):
       player 101 has score 40.
       count_higher(root, 40) counts both score=95 nodes -> higher_count = 2.
       returns 1 + 2 = 3.
    5. get_rank(105):
       player 105 has score 95.
       count_higher(root, 95) sees 95 > 95 is False on both 95 nodes -> higher_count = 0.
       returns 1 + 0 = 1 (tied for 1st with player 102!).
    6. get_top_k(2):
       first_k_ids visits (-95, 102) then (-95, 105) and halts since len == 2.
       returns [102, 105].
    
  9. Complete solution

    from typing import Any, Dict, List, Optional, Set, Tuple
    import random
    
    
    class TreapNode:
        def __init__(self, user_id: int, score: int, priority: float):
            self.user_id = user_id
            self.score = score
            # Composite BST key (-score, user_id): smaller tuple = higher score, or smaller user_id on ties.
            self.key: Tuple[int, int] = (-score, user_id)
            # Random max-heap priority keeps expected tree height O(log N) without manual rotations.
            self.priority = priority
            # Subtree node count (1 + left size + right size) for O(log N) rank counting.
            self.size = 1
            self.left: Optional["TreapNode"] = None
            self.right: Optional["TreapNode"] = None
    
    
    def subtree_size(node: Optional[TreapNode]) -> int:
        return node.size if node is not None else 0
    
    
    def refresh_size(node: TreapNode) -> None:
        # Recompute subtree count whenever `node.left` or `node.right` changes.
        node.size = 1 + subtree_size(node.left) + subtree_size(node.right)
    
    
    def split(
        node: Optional[TreapNode],
        pivot_key: Tuple[int, int],
    ) -> Tuple[Optional[TreapNode], Optional[TreapNode]]:
        """Partition `node` into two treaps: (keys < pivot_key, keys >= pivot_key)."""
        if node is None:
            return None, None
    
        if node.key < pivot_key:
            # `node` and its entire left subtree belong to the `< pivot_key` side.
            smaller_right, larger = split(node.right, pivot_key)
            node.right = smaller_right
            refresh_size(node)
            return node, larger
    
        # `node` and its entire right subtree belong to the `>= pivot_key` side.
        smaller, larger_left = split(node.left, pivot_key)
        node.left = larger_left
        refresh_size(node)
        return smaller, node
    
    
    def merge(
        left: Optional[TreapNode],
        right: Optional[TreapNode],
    ) -> Optional[TreapNode]:
        """Combine two treaps when every key in `left` is strictly smaller than every key in `right`."""
        if left is None:
            return right
        if right is None:
            return left
    
        # Keep the higher-priority root on top to preserve the max-heap invariant.
        if left.priority > right.priority:
            left.right = merge(left.right, right)
            refresh_size(left)
            return left
    
        right.left = merge(left, right.left)
        refresh_size(right)
        return right
    
    
    def erase(
        node: Optional[TreapNode],
        target_key: Tuple[int, int],
    ) -> Optional[TreapNode]:
        """Delete `target_key` from the treap and return the updated subtree root."""
        if node is None:
            return None
        if node.key == target_key:
            # Splice `node` out by merging its two ordered subtrees directly.
            return merge(node.left, node.right)
        if target_key < node.key:
            node.left = erase(node.left, target_key)
        else:
            node.right = erase(node.right, target_key)
        refresh_size(node)
        return node
    
    
    def count_higher(node: Optional[TreapNode], target_score: int) -> int:
        """Count how many users in the treap have `score > target_score`."""
        higher_count = 0
        while node is not None:
            # Compare raw scores (NOT full keys) so tied users never count as beating one another.
            if node.score > target_score:
                # Every node in `node.left` has key < node.key, so left.score >= node.score > target_score.
                higher_count += 1 + subtree_size(node.left)
                node = node.right
            else:
                # Here node.score <= target_score, and all of `node.right` has score <= node.score.
                node = node.left
        return higher_count
    
    
    def first_k_ids(root: Optional[TreapNode], k: int) -> List[int]:
        """Collect the first `k` user_ids via an iterative in-order walk that stops early."""
        top_ids: List[int] = []
        stack: List[TreapNode] = []
        node = root
    
        while len(top_ids) < k and (node is not None or stack):
            while node is not None:
                stack.append(node)
                node = node.left
            visited = stack.pop()
            top_ids.append(visited.user_id)
            node = visited.right
    
        return top_ids
    
    
    class Leaderboard:
        def __init__(self):
            # scores: dict mapping user_id -> current score, e.g. {101: 40, 105: 95}
            self.scores: Dict[int, int] = {}
            self.root: Optional[TreapNode] = None
            # Dedicated RNG keeps runs deterministic without touching global `random` state.
            self.rng = random.Random(0)
    
        def update_score(self, user_id: int, score: int) -> None:
            # Phase 1: If this user already has a score, remove their old key from the treap.
            if user_id in self.scores:
                old_score = self.scores[user_id]
                old_key = (-old_score, user_id)
                self.root = erase(self.root, old_key)
    
            # Phase 2: Record the new score and insert a fresh treap node in sorted key order.
            self.scores[user_id] = score
            new_node = TreapNode(user_id, score, self.rng.random())
            smaller, larger = split(self.root, new_node.key)
            self.root = merge(merge(smaller, new_node), larger)
    
        def get_rank(self, user_id: int) -> int:
            if user_id not in self.scores:
                return -1
            user_score = self.scores[user_id]
            return 1 + count_higher(self.root, user_score)
    
        def get_top_k(self, k: int) -> List[int]:
            return first_k_ids(self.root, k)
    
    
    def dynamic_leaderboard(
        operations: List[str],
        arguments: List[List[int]],
    ) -> List[object]:
        board = Leaderboard()
        results: List[object] = []
    
        for op, args in zip(operations, arguments):
            if op == "update_score":
                user_id = args[0]
                score = args[1]
                board.update_score(user_id, score)
                results.append(None)
            elif op == "get_rank":
                user_id = args[0]
                results.append(board.get_rank(user_id))
            elif op == "get_top_k":
                k = args[0]
                results.append(board.get_top_k(k))
            else:
                raise ValueError(f"unknown operation: {op}")
    
        return results
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Imagine managing a live arcade rankings board for 100,000 competitors whose ratings jump up and down continuously. If you pin player placards along a single physical rail, promoting someone forces you to slide thousands of placards down by hand. Instead, we arrange competitors in an order-statistic tree (a height-balanced binary search tree, where smaller keys branch left and larger keys branch right, augmented so every node also caches size, the count of nodes in its subtree). Because Python's standard library includes no balanced tree, we build a treap (a randomized search tree that pairs each node with a random priority so keys satisfy search-tree order while priorities satisfy max-heap order, keeping expected height O(log N)) ordered by the composite key (-score, user_id), alongside a hash map (self.scores mapping user_id -> score in average O(1) time).

Why do simpler structures hit a wall? Keeping only a hash map gives O(1) update_score, but every get_rank scans all N competitors (O(N)) and get_top_k must sort or heapify them. Keeping a sorted Python array lets bisect compute get_rank in O(log N), but every update_score deletes and inserts inside contiguous memory, shifting up to N entries in O(N) time. Pairing self.scores with a size-augmented treap lets update_score erase (-old_score, user_id) and insert (-new_score, user_id) in O(log N) expected time, while get_rank skips whole higher-scoring subtrees in O(log N) expected time.

Let's trace Example 1 ((101, 40), (105, 95), (102, 95), get_rank(101), get_rank(105), get_top_k(2)):

1. Insert (101, 40), (105, 95), (102, 95):
   Ordered treap keys: (-95, 102) < (-95, 105) < (-40, 101)

2. get_rank(101):
   scores[101] == 40. Walk root-to-leaf counting raw scores > 40:
   both score=95 nodes exceed 40 -> higher_count = 2 -> rank = 1 + 2 = 3.

3. get_rank(105):
   scores[105] == 95. Walk root-to-leaf counting raw scores > 95:
   zero nodes exceed 95 -> higher_count = 0 -> rank = 1 + 0 = 1.

4. get_top_k(2):
   In-order walk visits smallest keys first: (-95, 102), then (-95, 105), and stops -> [102, 105].

Complexity

Let N be the number of registered competitors currently on the scoreboard.

  • update_score(user_id, score) — Time: O(log N) expected. Checks self.scores in average O(1) time, then runs at most one erase, one split, and two merge operations, each traversing one root-to-leaf path of expected length O(log N).
  • get_rank(user_id) — Time: O(log N) expected. Fetches the competitor's score in O(1) average time and walks one root-to-leaf path in count_higher, adding entire left subtrees in O(1) via node.size.
  • get_top_k(k) — Time: O(k + log N) expected (O(min(k, N) + log N)). The stack-based in-order traversal descends the leftmost spine (O(log N) nodes) and visits at most k nodes before halting.
  • Space: O(N) total. Maintains one dictionary entry and one TreapNode per active competitor, plus O(log N) expected stack depth during tree operations. (Note: random.Random(0) makes unit tests reproducible; in a service exposed to adversarial inputs, initialize priorities from OS randomness such as random.SystemRandom() so priorities cannot be predicted.)

Edge cases

  • Unregistered user_id lookup: user_id not in self.scores returns -1 right away without altering the scoreboard (Examples 2 and 3).
  • Empty board or k <= 0: get_top_k cleanly returns [].
  • k exceeding registered competitors (k > N): The in-order walk exhausts the tree and returns all N competitors in rank order.
  • Overwriting an existing score (including identical values): Erasing (-old_score, user_id) prior to inserting (-score, user_id) prevents duplicate entries for the same competitor.
  • Multi-way score ties: Tied competitors receive identical ranks (1 + strictly higher), trailing ranks skip accordingly (95, 95, 40 yields ranks 1, 1, 3), and get_top_k breaks ties by ascending user_id.
  • Zero and negative scores: Negating score inside (-score, user_id) preserves exact numeric ordering across positive, zero, and negative integers.

Common mistakes

  • Leaving stale treap nodes behind on update_score: Forgetting to erase a player's old (-old_score, user_id) node causes duplicate appearances in get_top_k and inflated get_rank results.
  • Comparing full (-score, user_id) tuples inside count_higher: Treats tied players with smaller IDs as strictly ahead, wrongly assigning player 105 rank 2 instead of 1 in Example 1.
  • Using score alone as the BST key: Collides on score ties, complicating single-player removal and losing deterministic user_id ordering for get_top_k.
  • Skipping refresh_size(node) after child pointer edits: Preserves get_top_k order while silently corrupting subtree counts read by get_rank.
  • Re-sorting all N players on every get_top_k(k) call: Turns a tiny k = 10 lookup into an O(N log N) full scan.

Alternative approaches

  • Fenwick tree (Binary Indexed Tree) over score buckets: A Fenwick tree (an array-backed prefix-sum structure supporting point updates and prefix sums in O(log M) time) works well when scores lie in a compact integer interval [0, M) or can be coordinate-compressed ahead of time, though arbitrary dynamic integer scores and user_id-ordered get_top_k require per-score ordered buckets.
  • Sorted Python list with bisect (or sortedcontainers.SortedList): Keeping (-score, user_id) in a standard list gives O(log N) get_rank via bisect_left and O(k) slicing for get_top_k, but suffers O(N) array shifts on updates; third-party sortedcontainers.SortedList chunks the array into sqrt(N) blocks for O(sqrt(N)) updates when external packages are allowed.

Follow-up questions

  • How would you re-architect this scoreboard to support 100 million active players across multiple machines? Holding 100 million Python TreapNode objects and dictionary entries inside one process would require tens of gigabytes of RAM and saturate a single CPU core. Externalize state into distributed sorted-set shards — such as Redis Sorted Sets (implemented with a skip list, a multi-level linked structure supporting O(log N) updates and rank lookups) — partitioned by score bands (for instance, shard A covers < 1000, shard B covers 1000..4999, and so forth) paired with a hash-sharded user_id -> current_score store. Because each score-band shard tracks its total player count, any player's global rank equals the sum of player counts across all higher score bands (tiny metadata replicated everywhere) plus their local rank inside their current band.
  • What changes in time or space complexity if callers also ask for a player's percentile standing (such as top 5% or top 10%)? Answering a player's percentile keeps the exact same O(log N) expected time and O(N) space: get_rank(user_id) computes their 1-based rank in O(log N) and len(self.scores) gives total active players N in O(1), letting you return (rank - 1) / N (or rank / N) immediately. Even finding the threshold score for the top p% takes O(log N) time by descending the treap with subtree_size(node.left) to select the ceil((p / 100) * N)-th node.
  • How would you keep reads and writes safe under heavy concurrent traffic when thousands of score updates arrive per second? Mutating treap pointers during split, merge, and erase without synchronization exposes concurrent readers to half-rewired subtrees and stale size fields. A straightforward single-node design guards the structure with a reader-writer lock (allowing concurrent get_rank / get_top_k readers while serializing update_score writers), or funnels incoming (user_id, score, sequence_id) updates through a single-writer queue where one dedicated thread applies updates in O(log N) and periodically publishes read-only snapshots. When write throughput exceeds one core, hash-partition competitors across S independent treap shards by user_id % S for lock-free parallel writes and answer get_rank / get_top_k via scatter-gather (summing count_higher or merging top-k slices across all S shards in parallel).

Follow-up questions

Similar questions

More Anchorage Digital interview questions

All 3 Anchorage Digital questions →