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
UnverifiedIdea. 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.
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 probability1 / 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.