KatInterview

Random Index Selection by Given Weights

Heaps, Sorting & SearchModel answer
MediumModel answerHeaps, Sorting & Searchprefix-sumbinary-searchrandomization

Last updated

Design an index sampler where each element's probability of being chosen is proportional to its assigned weight.

You are provided with an array of positive integers weights, where weights[i] represents the relative weight of index i.

Design a data structure that samples an index i with probability proportional to weights[i]. That is, the probability of selecting index i must be exactly:

$$\frac{\text{weights}[i]}{\sum_{j=0}^{n-1} \text{weights}[j]}$$

Implement a class WeightedRandomSampler:

  • __init__(weights: List[int]): Initializes the object with the given sequence of positive integer weights. Preprocessing should take at most $\mathcal{O}(n)$ time.
  • pick_index() -> int: Returns a single random index in the range $[0, n-1]$. Each query should run in $\mathcal{O}(\log n)$ time.

Constraints & Rules

  • $1 \le n \le 10^5$, where $n$ is the length of weights.
  • $1 \le \text{weights}[i] \le 10^5$ for all $0 \le i < n$.
  • The sum of all weights will fit inside a standard 64-bit integer.
  • pick_index() can be called up to $10^4$ times per instance.

Example

sampler = WeightedRandomSampler([1, 3])
# pick_index() should return 0 with ~25% probability and 1 with ~75% probability.

sampler = WeightedRandomSampler([1, 2, 3, 4])
# Sum = 10. 
# Index 0 has probability 1/10 (10%)
# Index 1 has probability 2/10 (20%)
# Index 2 has probability 3/10 (30%)
# Index 3 has probability 4/10 (40%)

Hints

Hint 1

Consider mapping each index to a range on a continuous number line whose length corresponds to its weight.

Hint 2

What data structure lets you build cumulative ranges in linear time, and how can you quickly locate which range a random number falls into?

Hint 3

Pay close attention to boundaries: determine whether you are picking continuous floats or discrete integers, and ensure binary search bounds match that decision.