528. Random Pick with Weight
Asked at 22Meta87Amazon44Google44Apple35Microsoft30Bloomberg18Nuro87Waymo79Goldman Sachs21Two Sigma100Liftoff95Rubrik82Criteo78Shopee78Coinbase73Sony70Uber68LinkedIn61Coupang58PayPal51TikTok46Roblox37
Problem
Solution(w) gets positive weights. pickIndex() returns a random index i with probability w[i] / sum(w).
Example: w = [1,3] → pickIndex() returns 0 about 25% of the time and 1 about 75%
Constraints: n ≤ 10⁴; up to 10⁴ calls.
Prefix sums turn weights into intervals on [0, total). Draw r uniformly, binary-search the first prefix sum greater than r.
w = [1, 3] prefix = [1, 4]
r in [0,1) -> index 0 (25%) r in [1,4) -> index 1 (75%)
Complexity: O(n) init, O(log n) per pick.
class Solution:
def __init__(self, w: List[int]):
self.pre = list(itertools.accumulate(w))
def pickIndex(self) -> int:
r = random.random() * self.pre[-1]
return bisect.bisect_right(self.pre, r)
random.seed(1)
s = Solution([1, 3])
picks = [s.pickIndex() for _ in range(4000)]
assert set(picks) == {0, 1} and 0.70 < picks.count(1) / 4000 < 0.80
assert Solution([5]).pickIndex() == 0
class Solution {
private final int[] pre;
private final Random rnd = new Random(1);
public Solution(int[] w) {
pre = new int[w.length];
for (int i = 0, s = 0; i < w.length; i++) pre[i] = s += w[i];
}
public int pickIndex() {
int r = rnd.nextInt(pre[pre.length - 1]); // r in [0, total)
int lo = 0, hi = pre.length - 1;
while (lo < hi) { // first prefix > r
int mid = (lo + hi) / 2;
if (pre[mid] > r) hi = mid; else lo = mid + 1;
}
return lo;
}
}
type Solution struct {
pre []int // prefix sums of the weights
}
func Constructor(w []int) Solution {
pre := make([]int, len(w))
s := 0
for i, x := range w {
s += x
pre[i] = s
}
return Solution{pre}
}
func (this *Solution) PickIndex() int {
r := rand.Intn(this.pre[len(this.pre)-1]) // 0 <= r < total
return sort.SearchInts(this.pre, r+1) // first prefix sum > r
}