KatInterview

Implement Weighted Index Selector with Efficient Retrieval

Heaps, Sorting & SearchModel answer
MediumModel answerHeaps, Sorting & Searchbinary searchprefix sumrandom sampling

Last updated

Design a data structure that accepts an array of positive item weights and samples indices proportional to their relative weight values.

You are tasked with building a data structure that performs weighted random sampling over a set of non-negative item weights.

Given a list of positive integers weights, construct a class WeightedRandomSampler with two methods:

  1. __init__(self, weights: List[int]): Preprocesses the weight distribution.
  2. pick_index(self) -> int: Returns an index i in the range [0, len(weights) - 1] with probability proportional to weights[i] / total_weight.

Constraints

  • 1 <= weights.length <= 10^5
  • 1 <= weights[i] <= 10^5
  • pick_index will be invoked up to 10^4 times per instance.

Example

sampler = WeightedRandomSampler([2, 8])
# Weight totals 10.
# Index 0 has weight 2 -> 20% selection probability.
# Index 1 has weight 8 -> 80% selection probability.
sampler.pick_index() # Might return 1
sampler.pick_index() # Might return 1
sampler.pick_index() # Might return 0

Hints

Hint 1

Think of mapping each weight to a continuous interval on a total number line equal to the sum of all weights.

Hint 2

How can prefix sums help transform individual weight ranges into sorted threshold values?

Hint 3

Once you generate a uniform random value across the total weight range, which binary search variation correctly maps that value to the appropriate interval?