← Questions

Weighted random value generator

0
AmazonCodingLast asked Jan 2026

A coding interview question asked in Amazon's technical phone screen, last asked Jan 2026. It tests randomization, prefix sums and binary-search.

Given a set of values, each with a positive weight, build a generator that returns a random value with probability proportional to its weight. It is built once and then called many times, so each call must be fast.

Interface

Unless you agree on a different interface with the interviewer, assume:

  • WeightedRandom(items: list[tuple[str, float]]) — builds the generator from (value, weight) pairs.
  • next() -> str — returns one value; value v comes back with probability weight(v) / total weight.

Example

g = WeightedRandom([("a", 1), ("b", 3), ("c", 6)])
# prefix sums 1, 4, 10. Draw r uniformly in [0, 10):
# r in [0, 1) -> "a", [1, 4) -> "b", [4, 10) -> "c"
# so "a" 10%, "b" 30%, "c" 60% of the time

Constraints

  • Up to 10^5 values; weights are positive (integer or real).
  • Up to 10^6 calls to next.

Clarifying questions

  • Integer or real weights? Can a weight be 0?
  • Is the set fixed after construction, or can values be added, removed or re-weighted?
  • Is a seeded random source needed for reproducible tests?

What a strong answer covers

  • Prefix sums plus binary search: O(n) build, O(log n) per call. Mind the boundaries (r in [0, total) and the first prefix strictly greater than r).
  • The alias method for O(1) per call after O(n) build, and when it is worth the complexity.
  • Floating-point care when weights are real: the last bucket must catch r close to the total.
  • Testing a random function: inject the random source, check the boundaries deterministically, and run a chi-squared test (or compare observed frequencies with a tolerance) over many draws.

Follow-ups

  • Values are added, removed and re-weighted between calls. Use a Fenwick tree or balanced tree for O(log n) updates and draws.
  • Each value expires a fixed time after it was added and must no longer be returned. How do you keep the totals right?
  • Draw k distinct values in proportion to their weights.

Where it's asked

  • Amazon · Technical phone screen · Last asked Jan 202660 min · Live coding in a shared editor that does not run code, plus Leadership Principles questions · No AI

What it tests

randomization · prefix sums · binary-search

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding