SDE & MLE Prep

528. Random Pick with Weight

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)