Design a dynamic leaderboard with rank queries
Company: Anchorage Digital
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Technical Screen
Quick Answer: This question evaluates proficiency with dynamic data structures and order-statistics, including maintaining sorted order under updates, deterministic tie-breaking, and analyzing time complexity for rank and top-K operations.
Constraints
- 0 <= len(operations) <= 100000
- At most 100000 elements are active at any time
- -1000000000 <= id <= 1000000000
- -1000000000 <= score <= 1000000000
- 0 <= k <= 100000
- The total number of ids returned across all topK operations is at most 200000
Examples
Input: ([[1,101,50],[1,102,70],[1,103,70],[3,2],[4,103],[4,101]],)
Expected Output: [[102,103],[2],[3]]
Explanation: Players 102 and 103 both have score 70, so id 102 ranks before id 103. Player 101 has score 50 and ranks third.
Input: ([[1,5,10],[1,2,20],[1,8,15],[4,5],[1,5,25],[3,5],[2,2],[4,2],[3,2]],)
Expected Output: [[3],[5,2,8],[-1],[5,8]]
Explanation: Initially id 5 ranks third. After updating id 5 to score 25, the order is 5, 2, 8. Removing id 2 makes its rank -1, leaving 5 then 8.
Input: ([[3,3],[4,1],[2,1],[1,1,0],[3,0],[4,1]],)
Expected Output: [[],[-1],[],[1]]
Explanation: TopK on an empty leaderboard returns an empty list, and a missing id has rank -1. topK(0) also returns an empty list.
Input: ([[1,-1,-5],[1,3,-5],[1,2,-10],[3,10],[4,2],[1,2,-5],[3,3],[2,-1],[4,3]],)
Expected Output: [[-1,3,2],[3],[-1,2,3],[2]]
Explanation: Negative scores are valid. With equal score -5, ids are ordered ascending, so -1 comes before 3, and later -1, 2, 3 are ordered by id.
Input: ([[1,1,100],[1,1,50],[1,2,50],[1,0,50],[3,10],[4,1],[2,42],[2,0],[3,10]],)
Expected Output: [[0,1,2],[2],[1,2]]
Explanation: Updating an existing id replaces its old score. When ids 0, 1, and 2 all have score 50, they rank in id order. Removing a nonexistent id does nothing.
Hints
- Convert the ranking rule into a normal ascending sort key: (-score, id). Smaller keys are better ranks.
- You need a structure that can count how many active keys are before a given key and can find the k-th active key. An order-statistics tree works; since all operations are known, coordinate compression plus a Fenwick tree is also possible.