KatInterview

Design a Weighted Sampling Generator with Dynamic Updates

Data Structure DesignModel answer
MediumModel answerData Structure Designdesign-dsheaps-sortingmath-bits

Last updated

Implement a class for weighted sampling that supports O(1) sampling for static inputs and logarithmic updates for dynamic environments.

Create a data structure that accepts a list of positive integer weights $W$ of length $N$ and implements a pick() function. Each call to pick() should return index $i$ with probability proportional to $W[i]$, i.e., $P(i) = \frac{W[i]}{\sum_{j=0}^{N-1} W[j]}$.

Your design should address two scenarios:

  1. Static Case: Preprocessing is done once on $N \le 10^5$ items, followed by up to $10^7$ pick() operations. Optimize pick() execution time.
  2. Dynamic Extension: Support an additional operation update(index, delta) that modifies the weight at index by adding delta (where the new weight remains positive). Both update() and pick() must run in sublinear time $O(\log N)$.

Discuss choices regarding algorithmic strategies (e.g., cumulative sum arrays vs. alias sampling), integer random sampling precision, bit manipulation tricks, and complexity trade-offs.

Hints

Hint 1

For static weights, how can you partition sample spaces into equal-sized buckets to achieve O(1) sampling time?

Hint 2

To handle integer precision issues with random floats, how can integer range draws guarantee exact probability distribution?

Hint 3

For dynamic updates, consider how a Binary Indexed Tree (Fenwick Tree) allows bitwise binary searching over running totals in O(log N) time.