Random Pick with Weight
Problem
You are given an array w of positive integers where w[i] is the weight of index i. Design a class with a constructor that takes w and a method pickIndex() that returns an index in [0, len(w) - 1] at random, such that index i is chosen with probability w[i] / sum(w). pickIndex will be called many times, so it should be fast.
- The weight array is non-empty and has at most 50,000 entries.
- Every weight is a positive integer (strictly increasing prefix sums depend on this); weights can be as large as a million.
- Expect tens of thousands of
pickIndexcalls on one instance.
Examples
w = [6]→pickIndex()always returns0.w = [3, 1]→ returns0with probability 3/4 and1with probability 1/4.w = [4, 1, 5]→ returns0,1,2with probabilities 0.4, 0.1, 0.5 respectively.
Hints
- Imagine laying the weights end to end as segments on a number line from 0 to the total. Throwing a dart uniformly at the line lands in segment
iwith probability proportional tow[i]. - The right endpoints of those segments form a sorted array. Given the dart's position, how do you find which segment it hit?
- Build a prefix-sum array of the weights; draw a uniform number in
(0, total]; binary search for the first prefix that is at least the draw.
Last reviewed 8 September 2026
Approach · Solution (Python) · Complexity · Follow-ups · Company variations · Tests
The rest of this question — the worked approach, the Python solution with passing tests, complexity, follow-ups and how each company frames it — is part of the guides.
Get the full guide
Pick the company you're interviewing with. Each guide has every question tiered for that loop — one-time purchase, lifetime access.
Also in: Apple, Google, Meta, Microsoft, Netflix
Interviewing at more than one? All 6 guides for $499 · save $395
Not ready to buy? Get the free starter pack — 13 questions with full solutions.