KatInterview

Maintain Dynamic Multiset with Rank Queries

Data Structure DesignAuto-graded · 18 test cases
MediumAuto-gradedData Structure Designfenwick-treebinary-indexed-treerank-queries

Last 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:

  1. Insert a value into the collection.
  2. 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 where arguments[i] contains the parameter(s) for operations[i]:
    • For "insert": a single-element list [val] where val is the integer to add.
    • For "get_kth_largest": a single-element list [k] where k is the rank to query.

Return Value

A list containing one entry per operation:

  • None for 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 k is always valid: 1 ≤ k ≤ current number of elements.

Constraints

  • Up to 10^5 insert operations.
  • Up to 10^5 query 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.