The 60-second answer
Build prefix sums of weights so each index owns an interval proportional to its weight. Draw a uniform sample over the total mass and binary-search the first prefix boundary that contains it.
Build the answer in this order
Build prefix sums of weights so each index owns an interval proportional to its weight.
Draw a uniform sample over the total mass and binary-search the first prefix boundary that contains it.
Preprocessing is O(n), each draw is O(log n), and storage is O(n).
Test zero weights, integer vs floating-point mass, deterministic seeds, and empirical frequency convergence.
A useful interview mental model
This is the shape of a strong answer—not a script to memorize.
Senior-level signal
- For update-heavy workloads, use a Fenwick/segment tree; for huge read volume, consider the alias method.
- Discuss testing randomized code statistically as well as with deterministic structural tests.
What the interviewer is really testing
Likely follow-up questions
Common weak-answer patterns
- Starting to code before constraints are clear.
- Giving complexity without explaining why it is correct.
- Skipping adversarial and boundary cases.