Maintain Dynamic Multiset with Rank Queries
Data Structure DesignAuto-graded · 18 test casesLast updated
Tests the ability to build a structure that handles insertions and k-th largest queries efficiently using a Fenwick tree over the value domain.
Problem Statement
Build a system that manages a collection of integers allowing duplicates and supports two operations:
- Insert a value into the collection.
- Query the k-th largest element currently stored.
You will implement a function that processes a sequence of these operations and returns the results of all queries.
Function Signature
def dynamic_rank_query(operations: List[str], arguments: List[List[int]]) -> List[Optional[int]]:
Parameters
operations: A list of operation names, each either"insert"or"get_kth_largest".arguments: A list wherearguments[i]contains the parameter(s) foroperations[i]:- For
"insert": a single-element list[val]wherevalis the integer to add. - For
"get_kth_largest": a single-element list[k]wherekis the rank to query.
- For
Return Value
A list containing one entry per operation:
Nonefor each"insert"operation.- The k-th largest element (an integer) for each
"get_kth_largest"operation.
Any operation name other than the two recognized types should be ignored and produce no output entry.
Behavior
- The collection starts empty.
- Duplicates are retained as separate elements. If the collection contains
[10, 10, 20], the 1st largest is 20, the 2nd largest is 10, and the 3rd largest is 10. - You may assume
kis always valid:1 ≤ k ≤ current number of elements.
Constraints
- Up to
10^5insert operations. - Up to
10^5query operations. - Each value is in the range
[-10^6, 10^6]. - Total operations (inserts + queries): up to
2 × 10^5.
Performance Goals
Aim for sublinear time per operation. A solution that sorts the entire collection on every query will be too slow.
Examples
Example 1
Input: dynamic_rank_query(['insert', 'insert', 'insert', 'get_kth_largest', 'get_kth_largest', 'get_kth_largest'], [[10], [20], [10], [1], [2], [3]])
Output: [None, None, None, 20, 10, 10]
Example 2
Input: dynamic_rank_query(['insert', 'insert', 'insert', 'insert', 'get_kth_largest', 'get_kth_largest', 'get_kth_largest'], [[-5], [7], [-5], [0], [1], [3], [4]])
Output: [None, None, None, None, 7, -5, -5]
Hints
Hint 1
The value range is bounded and relatively small. Can you use the values themselves as indices?
Hint 2
Convert k-th largest to an equivalent smallest-rank query: the k-th largest among n elements is the (n - k + 1)-th smallest.
Hint 3
A Fenwick tree (Binary Indexed Tree) can track counts by value and support efficient rank queries via descent, not just prefix sums.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Solution Approach
The challenge is to support both insertion and rank queries efficiently when each operation can happen up to 10^5 times. Sorting on every query or maintaining a sorted list with linear-time insertions will both exceed time limits.
Key Insight: Exploit the Bounded Value Range
The values lie in [-10^6, 10^6], a range of about 2 million distinct integers. Instead of comparing elements, we can use values as direct indices into a counting structure.
Strategy
-
Shift values to positive indices. Map each value
valtoval + 1_000_001. This transforms the range[-10^6, 10^6]into[1, 2_000_001], suitable for a 1-indexed Fenwick tree. -
Use a Fenwick tree to store counts. Each position in the tree tracks how many times the corresponding value appears in the collection. Duplicates increment the same position multiple times.
-
Insert operation. Perform a Fenwick point update (add 1 at the shifted index). This takes
O(log U)time, whereU ≈ 2 × 10^6. -
Query operation. The k-th largest among
nelements is equivalent to the(n - k + 1)-th smallest. To find the r-th smallest efficiently:- Walk down the implicit binary structure of the Fenwick tree.
- Start with
index = 0andstepequal to the largest power of two ≤size. - At each step, check if jumping to
index + stepwould still have a prefix sum less thanr. If so, take the jump and reducerby the count at that position. - Halve
stepand repeat. - When finished,
index + 1is the position of the r-th smallest element.
-
Unshift the result. Subtract the offset to recover the original value.
Why This Works
The Fenwick tree descent leverages the tree's internal structure to perform a rank-to-index lookup in O(log U) time, avoiding the O(log² U) cost of binary searching over prefix sums. Each step of the descent corresponds to a bit in the binary representation of the final index, making the walk a greedy bit-by-bit search.
Because counts are non-negative, prefix sums are monotone, guaranteeing the descent finds the correct position. Duplicates are naturally handled since ranks count individual occurrences.
Complexity
- Time per insert:
O(log U)whereU ≈ 2 × 10^6, about 21 tree updates. - Time per query:
O(log U), about 21 descent steps. - Overall time:
O((inserts + queries) · log U), roughly 4 million operations for 200,000 total operations. - Space:
O(U)for the tree array, about 2 million integers allocated upfront.
Implementation
from typing import List, Optional
def dynamic_rank_query(operations: List[str], arguments: List[List[int]]) -> List[Optional[int]]:
offset = 1_000_001
size = 2_000_001
tree = [0] * (size + 1)
total = 0
result = []
def add(index: int) -> None:
while index <= size:
tree[index] += 1
index += index & -index
def kth_smallest(rank: int) -> int:
index = 0
step = 1 << (size.bit_length() - 1)
while step:
candidate = index + step
if candidate <= size and tree[candidate] < rank:
index = candidate
rank -= tree[candidate]
step >>= 1
return index + 1
for operation, args in zip(operations, arguments):
if operation == "insert":
add(args[0] + offset)
total += 1
result.append(None)
elif operation == "get_kth_largest":
k = args[0]
result.append(kth_smallest(total - k + 1) - offset)
return result