Math Fundamentals18 sections · 814 units
Open in Course

Problem - Random Pick Index

Reservoir sampling variant

Given an integer array with possible duplicates, you need to randomly return an index of a given target value. Each occurrence must have equal probability of being chosen.

For example, if the array is [1,2,3,3,3][1, 2, 3, 3, 3] and target is 33, you should return index 22, 33, or 44 with equal probability 13\frac{1}{3} each.

The challenge: the array is given once in the constructor. How can you pick fairly without preprocessing all target values?