Skip to content
DSA Patterns
Menu
Language
Reservoir SamplingLC #5285 of 6← PreviousNext →

Demo preview: These solutions pass the automated test suite but have not been human-reviewed. Treat trade-offs and prose as draft.

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

Unverified
Time O(n) ctor, O(log n) pickSpace O(n)

Idea. 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.

Solution
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 x in [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 is O(log n).
Contributor review checklist

Interactive

Mental model

A worked animation for this problem. Scrub steps or press space to pause; re-tell the invariant out loud.

Step 1 of 6
1/6

Pick index i with probability w[i]/sum(w). Weights [1,3], total 4.

1
0
3
1

P(0)=1/4 P(1)=3/4

Key:CurrentActive rangeMatchSettled