KatInterview

Build a Biased Index Picker Using Cumulative Totals

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

Last updated

Design a class that returns an index at random with probability proportional to its weight, then explain how to make each draw fast and how to handle updates.

Biased Index Picker

You are given a list of positive integers weights. The entry weights[i] is the weight of position i. Design a class WeightedSampler that returns positions at random so that position i is returned with probability weights[i] / sum(weights).

The class must expose:

  • __init__(self, weights: List[int]): stores or preprocesses the weights.
  • pick_index(self) -> int: returns one random position, following the distribution above. Each call is independent of earlier calls.

Constraints

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

Example

sampler = WeightedSampler([1, 3])
# pick_index() should return 0 about 25% of the time
# and 1 about 75% of the time.

Edge cases to address

  • A list with a single weight.
  • Large weights and totals: discuss integer overflow in languages with fixed-width integers.

What is expected

Describe your approach and justify why the resulting distribution is exactly right. Give the time and space complexity of both methods, and write working code. Be ready to discuss these follow-ups:

  1. How would you support changing a weight after construction?
  2. How would you reduce memory if the weights are extremely sparse?
  3. How does a single-pass, no-preprocessing method compare, and when would you prefer it?

Hints

Hint 1

Picture the weights as consecutive segments laid along a line, where segment i has length weights[i]. What happens if you choose a uniformly random point on that line?

Hint 2

Store running totals. Because every weight is positive, the totals are strictly increasing, so you can locate the segment containing a random number with binary search instead of a scan.

Hint 3

Make sure the range you draw from and the binary-search variant agree. Drawing from 1..total pairs with 'first total >= r' (bisect_left); drawing from 0..total-1 pairs with 'first total > r' (bisect_right). Mixing them skews the probabilities.