Random Pick Index

Medium · Math · Hash Table · Math · Reservoir Sampling · Randomized

Problem

Design a class that, given an integer array that may contain duplicates, returns a uniformly random index of a requested value.

Implement Solution:

Because results are random, the examples show one possible outcome. The grader checks that every pick is a valid index and, over long runs, that each index of a target comes up about equally often.

Examples

Input: ops = ["Solution","pick","pick","pick"], args = [[[5,2,5,9,5]],[5],[2],[9]]
Output: [None, 2, 1, 3] (one possible outcome)

pick(5) may return 0, 2 or 4, each with chance 1/3; 2 and 9 each occur once, at indices 1 and 3.

Input: ops = ["Solution","pick","pick"], args = [[[7,7]],[7],[7]]
Output: [None, 1, 1] (one possible outcome)

Each call independently returns 0 or 1 with chance 1/2.

Constraints

Approaches

Follow-up

The index-list map trades O(n) memory for O(1) picks; reservoir sampling uses O(1) memory and O(n) per pick. The use cases take the randomness out: the first answers "which index is the k-th occurrence", the second replays reservoir sampling with the random numbers given.

Related problems

Start free on Cariara · Coding problems · System design studio

Starting Python
No results yet.

          
↑↓ move ↵ open esc close

Labs

Loading labs…

Run with your own input

Starting Python

Loading Python…