Design dynamic weighted random sampling with updates
CitadelSoftware Engineer · OnsiteLast updated
This question evaluates a candidate's ability to design and analyze dynamic data structures that support weighted random sampling with inserts and deletes, testing skills in algorithm design, complexity analysis, and randomized sampling under large numeric constraints.
Problem: Support weighted random sampling with insert/delete
Design a data structure that maintains a dynamic set of items, each with a positive integer weight, and supports:
insert(id, weight)
- Adds a new item
idwith the givenweight. - If
idalready exists, you may either reject or treat it as an update (state your choice).
delete(id)
- Removes the item if it exists.
sample() -> id
- Returns an
idchosen randomly such that:
[ P(id) = \frac{weight(id)}{\sum_j weight(j)} ]
Requirements
- Target time complexity: O(log n) per operation.
- Must handle up to ~10^5 operations.
- Weights can be large (e.g., up to 10^9); total weight may exceed 32-bit.
sample()should be unbiased given an ideal RNG.
Notes
- You may assume access to a function
randInt(1, totalWeight)that returns a uniform integer in that range. - Clearly define how you map item IDs to internal indices as the set changes over time.
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.