---
title: Sampling indices from a weighted (multinomial) distribution
url: https://gurkanozkan.ai/learn/coding/mle-sampling-indices-from-a-weighted-multinomial-distribution-30/
markdown: https://gurkanozkan.ai/learn/coding/mle-sampling-indices-from-a-weighted-multinomial-distribution-30.md
kind: coding
difficulty: Easy
topics:
  - Sampling
  - Binary search
json: https://gurkanozkan.ai/api/learn/coding/mle-sampling-indices-from-a-weighted-multinomial-distribution-30.json
robots: noindex
---

# Sampling indices from a weighted (multinomial) distribution

Weights are non-negative with a positive total. For each `u` in `us` (each in [0, 1)), return the smallest index `i` whose cumulative weight `cum[i] > u·total`. Raise `ValueError` for a negative weight or an all-zero total. Aim for O(n) setup and O(log n) per draw.

## Signature

```python
def sample_indices(weights: list[float], us: list[float]) -> list[int]: ...
```

## Examples

Each call and the value it should give.

```python
>>> sample_indices([1, 1, 2], [0.0, 0.24, 0.25, 0.49, 0.5, 0.999]) == [0, 0, 1, 1, 2, 2]
True

>>> sample_indices([0, 3, 0, 1], [0.0, 0.5, 0.75, 0.9]) == [1, 1, 3, 3]
True
```

## Hints

1. Prefix-sum the weights; for each u find the first index with cum[i] > u * total via bisect_right.
2. Raise ValueError for a negative weight or an all-zero total.
3. Zero-weight items are never selected — bisect_left is the trap.

## Reference solution

```python
import bisect

def sample_indices(weights, us):
    cum = []
    s = 0.0
    for w in weights:
        if w < 0:
            raise ValueError("negative weight")
        s += w; cum.append(s)
    if s == 0:
        raise ValueError("all-zero weights")
    return [bisect.bisect_right(cum, u * s) for u in us]
```

## What a strong solution covers

- Prefix sums plus `bisect_right`, so zero-weight items are never selected.
- Validates inputs.
- Discusses the alias method (O(1) per draw), numerical drift in prefix sums, and Gumbel-max sampling.

## Common mistakes

- `bisect_left`, which can select zero-weight items at boundaries
- linear scans per draw.
---

*Study material compiled with AI: drafted by a local model (Inkling 2 Mini) from public sources, then checked against those sources by independent AI reviewers (Claude) in November 2026. Not reviewed line by line by a person.*
