Skip to content
DSA Patterns
Menu
Language
Reservoir SamplingLC #3983 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 Index

Problem (restated)

Given a fixed array, pick(target) returns a uniformly random index i with nums[i] == target. Target may appear many times.

Intuition

You can index every occurrence up front, but reservoir sampling k=1 needs no extra map: scan once, and among the matches seen so far replace the chosen index with probability 1/count.

Approaches

Reservoir on matching indices

Unverified
Time O(n) pickSpace O(1)

Idea. Walk nums. Skip non-targets. For the c-th match, keep its index when rand(c) == 0. After all matches, each matching index was chosen with probability 1/c.

Walkthrough. nums = [1,2,3,3,3], pick(3). Matches at 2,3,4. First kept; then 1/2; then 1/3. Each of 2,3,4 equally likely.

Trade-offs. Precomputing target → [indices] is O(1) pick after O(n) space. Reservoir is O(1) extra space per query; right when the array is huge or streaming.

Solution
export class Solution {
  private nums: number[];

  constructor(nums: number[]) {
    this.nums = nums;
  }

  pick(target: number): number {
    let chosen = 0;
    let count = 0;
    for (let i = 0; i < this.nums.length; i++) {
      if (this.nums[i] !== target) continue;
      count++;
      if (Math.floor(Math.random() * count) === 0) chosen = i;
    }
    return chosen;
  }
}
export class Solution {
  private nums: number[];

  constructor(nums: number[]) {
    this.nums = nums;
  }

  pick(target: number): number {
    let chosen = 0;
    let count = 0;
    for (let i = 0; i < this.nums.length; i++) {
      if (this.nums[i] !== target) continue;
      count++;
      if (Math.floor(Math.random() * count) === 0) chosen = i;
    }
    return chosen;
  }
}

Template connection

Pick-one (k=1) on the Reservoir Sampling page, filtered to a stream of matching indices instead of every item.

Reflection

  • On the c-th index equal to the target, keep it when rand(c) == 0. Each match ends up chosen with probability 1 / c.
  • The first match is a certain candidate. One match is that index. The problem does not call pick when nothing matches.
  • Storing the matches and scanning them again gives the same distribution. The reservoir does it in one pass.
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(3) on [1,2,3,3,3]. Return a uniform matching index, O(1) extra memory.

1
0
2
1
3
2
3
3
3
4

target = 3

Key:CurrentActive rangeMatchSettledEliminated