KatInterview

Weighted Random Picker for Unbounded Integer Scores

Data Structure DesignModel answer
MediumModel answerData Structure Designrandomized-algorithmsprefix-sumbinary-search

Last updated

Build a picker that returns an item with probability proportional to its weight, even when weights and their total exceed 32-bit or 64-bit limits, and discuss precision and memory trade-offs.

Weighted Random Picker

A recommendation service has a list of candidate items, each with a non-negative integer score. It must repeatedly choose one item at random, where the chance of choosing an item equals its score divided by the sum of all scores. Scores have no fixed upper bound, so a single score, or the total, can be far larger than a 32-bit or even a 64-bit integer.

Task

Design a class WeightedSampler:

  • WeightedSampler(items, weights) builds the picker from a list of items and a parallel list of non-negative integer weights.
  • pick() returns one item, where item i is returned with probability exactly weights[i] / sum(weights).

Requirements

  • Items with weight 0 must never be returned, wherever they appear in the list (first, last, or in a run).
  • Behavior must be defined for invalid input: an empty list, all-zero weights, negative weights, or mismatched list lengths.
  • Many pick() calls will follow a single construction, so make picks fast.

Discussion expected

  1. Describe your approach and the complexity of building and picking.
  2. Explain what breaks when weights exceed 32-bit limits, and what you would do about it (wider integers, big integers, rescaling, floating point, logs).
  3. Explain how the random draw itself can introduce bias when the total is huge.
  4. Compare memory and speed of at least two structures, and say what you would change if weights were updated frequently.

Provide code for your chosen approach.

Hints

Hint 1

Imagine laying the items' weights end to end on a number line. Each item owns a segment whose length equals its weight. What happens if you pick a uniform point on the whole line?

Hint 2

Store inclusive prefix sums and find the segment containing a random integer r in [0, total) using binary search. Think about which bisect variant (left or right) skips zero-weight items correctly.

Hint 3

Check where precision is lost: the sums, and the random number itself. A float random in [0,1) multiplied by the total only has about 2^53 distinct outcomes, and `rand() % total` is biased. Draw an exact uniform integer instead.

Hint 4

For many picks on static weights, consider the alias method for O(1) picks. For frequently changing weights, consider a Fenwick tree with a top-down descent.