KatInterview

Weighted Random Picker with Live Weight Updates

Data Structure DesignModel answer
MediumModel answerData Structure Designweighted-samplingfenwick-treeprefix-sums

Last updated

Design a sampler that picks an index in proportion to its weight, supports weight changes, draws several distinct items, and can be seeded and tested statistically.

Weighted Picker

A game studio has k collectible types, numbered 0 to k-1. Type i has a non-negative integer rarity weight w[i]. Design a class that picks types at random in proportion to those weights.

Core requirements

  • Picker(w): build the internal state in O(k) time.
  • pick(): return an index i with probability exactly w[i] / sum(w). The target is O(log k) per call, using prefix sums together with a search on a random target.

Follow-ups

  1. Live updates. Add update(i, delta), which adds delta to w[i]. pick() must stay at O(log k). Choose a data structure and justify it (a Fenwick tree and a segment tree are both candidates).
  2. Distinct draws. Add pickDistinct(t), which returns t different indices. Each draw must be proportional to the current weights of the items not yet chosen. Update internal state efficiently after each draw.
  3. Reproducibility and testing. Make the randomness seedable. Describe and write property-based tests that check the empirical distribution against the expected one within a stated tolerance. Cover these edge cases: zero weights, very large weights, all weights equal, and k = 1.

What to cover in your answer

  • The approach and why the probabilities are exact.
  • Complexity of every operation.
  • Behaviour for invalid input (empty list, negative resulting weight, total weight 0, t too large).
  • Code for the full class.

Hints

Hint 1

Give every index a segment of the integer range [0, total) whose length equals its weight. If you choose a uniform integer in that range, which segment contains it?

Hint 2

A static prefix array supports binary search but needs O(k) work per update. A Fenwick tree keeps partial sums so that updates and 'find the first prefix exceeding r' both take O(log k). You can search by descending the tree bit by bit instead of nesting a binary search around prefix queries.

Hint 3

For distinct draws, temporarily set the chosen item's weight to zero via update, and restore all removed weights at the end (use try/finally). For tests, inject a seeded RNG, use integer targets rather than floats, and compare observed frequencies to expected ones within a few standard deviations.