KatInterview

Proportional Random Index Picker with Fast Repeated Queries

Data Structure DesignModel answer
MediumModel answerData Structure Designprefix-sumsbinary-searchrandom-sampling

Last updated

Design a class that returns a random index with probability proportional to its weight, optimized for many repeated draws after one-time setup.

Proportional Index Picker

You are given an array of positive integer weights. Build a class ProportionalPicker that, on each call, returns an index chosen at random so that index i is returned with probability weights[i] / sum(weights).

Interface

  • __init__(self, weights: List[int]): performs any one-time preparation on the weights.
  • draw(self) -> int: returns one random index according to the weight distribution.

Expectations

  • Setup must be fast enough for large inputs.
  • draw will be called many times, so it should be asymptotically better than scanning all weights on every call.

Example

picker = ProportionalPicker([1, 3])
picker.draw()  # returns 0 about 25% of the time, 1 about 75% of the time

Constraints

  • 1 <= len(weights) <= 10^5
  • 1 <= weights[i] <= 10^5
  • draw is called at most 10^4 times.

Edge Cases to Consider

  • Only one weight in the list.
  • Totals that exceed 32-bit range (up to 10^10) in fixed-width languages.

What to Cover in Your Answer

  1. Your approach and why the probabilities come out exactly right.
  2. Time and space complexity of setup and of each draw.
  3. Working code.
  4. How you would adapt the design if weights could be updated between draws.

Hints

Hint 1

Imagine laying the weights side by side on a number line, so each index owns a stretch whose length equals its weight. What happens if you choose a uniformly random point on the whole line?

Hint 2

Precompute running totals of the weights. Because every weight is positive, those totals are strictly increasing, which means you can search them rather than scan them.

Hint 3

Be careful with off-by-one pairing: a random integer in [1, total] pairs with 'first position whose running total is >= target'. Prefer integer targets over scaling a float to avoid bias.