Random Pick with Weight
Problem (restated)
Given positive weights w, pickIndex() returns index i with probability w[i] / sum(w).
Intuition
Uniform sampling is a random integer in [1, total]. Prefix sums turn each index into a half-open range on that line. Binary search (lower bound) finds the first prefix >= x.
Approaches
Prefix sums + binary search
UnverifiedIdea. pref[i] = w[0]+…+w[i]. Draw x in [1, pref[n-1]]. Lower-bound x in pref; that slot owns the range (pref[i-1], pref[i]].
Walkthrough. w = [1,3], prefixes [1,4]. x=1 → 0; x=2,3,4 → 1. Odds 1:3.
Trade-offs. Alias method is O(1) pick after O(n) setup; prefix + binary search is the interview default. Linear scan of prefixes is correct but O(n) per pick.
export class Solution {
private pref: number[];
constructor(w: number[]) {
this.pref = new Array(w.length);
this.pref[0] = w[0]!;
for (let i = 1; i < w.length; i++) this.pref[i] = this.pref[i - 1]! + w[i]!;
}
pickIndex(): number {
const x = Math.floor(Math.random() * this.pref[this.pref.length - 1]!) + 1;
let lo = 0;
let hi = this.pref.length;
while (lo < hi) {
const mid = (lo + hi) >> 1;
if (this.pref[mid]! < x) lo = mid + 1;
else hi = mid;
}
return lo;
}
}
export class Solution {
private pref: number[];
constructor(w: number[]) {
this.pref = new Array(w.length);
this.pref[0] = w[0]!;
for (let i = 1; i < w.length; i++) this.pref[i] = this.pref[i - 1]! + w[i]!;
}
pickIndex(): number {
const x = Math.floor(Math.random() * this.pref[this.pref.length - 1]!) + 1;
let lo = 0;
let hi = this.pref.length;
while (lo < hi) {
const mid = (lo + hi) >> 1;
if (this.pref[mid]! < x) lo = mid + 1;
else hi = mid;
}
return lo;
}
}
Template connection
Weighted pick on the Reservoir Sampling page: prefix sums plus binary search (the alias method is the same idea with O(1) probes).
Reflection
- Build the prefix of the weights. Draw
xin[1, total]and take the first index whose prefix is>= x. That slot owns(previous, prefix]. - A weight of 0 is never chosen. The total is not 0. One positive weight is that index.
- The draw is proportional to the weight, not uniform. Building the prefix is
O(n). Each pick isO(log n).