KatInterview

Weighted Random Picker with Live Weight Updates

Data Structure DesignModel answer
MediumModel answerData Structure Designfenwick-treeprefix-sumsrandom-sampling

Last updated

Build a container that returns items at random with probability proportional to their weights, supports re-weighting existing items, and keeps picks fast and memory small.

Weighted Random Picker

Design a class WeightedPicker that stores named items with positive integer weights and can return a random item, where each item's chance of being returned equals its weight divided by the sum of all weights.

Required operations

  1. add_item(item: str, weight: int) inserts the item with the given weight. If the item is already stored, its weight is replaced by the new value (it is not added to the old one, and no duplicate entry is created).
  2. pick_item() -> str returns one item at random, using the probabilities described above.

Constraints

  • Weights are positive integers.
  • pick_item() should run in O(log N) time or better, where N is the number of distinct items.
  • Memory use should stay low even when N is very large.

Example

picker = WeightedPicker()
picker.add_item("red", 1)
picker.add_item("blue", 3)

# Over many calls to pick_item():
#   "red"  appears about 25% of the time  (1 / 4)
#   "blue" appears about 75% of the time  (3 / 4)

What to discuss

  • What should pick_item() do when nothing has been added?
  • Suppose the workload has many more add_item calls than pick_item calls, or the reverse. How does your design behave in each case?
  • What should happen if a caller tries to set a weight to zero or a negative number?

Give your approach, its complexity, and working code.

Hints

Hint 1

Picture the weights laid end to end on a number line of length equal to the total. If you draw a uniform integer in [0, total), which item's segment contains it?

Hint 2

A sorted array of cumulative sums plus binary search makes picks O(log N), but changing one weight forces you to rewrite every later cumulative value. Which structure supports both prefix queries and point updates in O(log N)?

Hint 3

A Fenwick (binary indexed) tree can be searched directly: walk down by decreasing powers of two, absorbing a block whenever its sum is not larger than the remaining random value. Use a dictionary from item to position so that re-adding an item becomes a delta update.