← Questions
Weighted random value generator
0
I was asked this
No reports yet. Sign in to say where you were asked it.
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; valuevcomes back with probabilityweight(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 (
rin[0, total)and the first prefix strictly greater thanr). - 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
rclose 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
kdistinct 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
No official answer yet. Write yours on the right and run it.
Nothing published yet.
Sign in to submit your code; every attempt is kept here.
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
