Random Pick Index
Given an integer array nums that may contain duplicates, implement pick(target): return a random index i such that nums[i] == target, with every matching index equally likely to be returned. It is guaranteed target exists in nums.
Open official problem prompt ↗Return one index uniformly at random among all positions equal to target, using only constant extra memory per query.
Interviewing candidates one at a time and, at the c-th qualified candidate, giving them the job with probability 1/c — everyone who ever qualified ends up equally likely to hold the offer.
- Input
- nums = [1,2,3,3,3]; calls = pick(3), pick(1), pick(3)
- Output
- [4, 0, 2]
- Why
- pick(3) may return any of indices 2, 3, or 4 each with probability 1/3 (here 4); pick(1) must return the only match, index 0; pick(3) again returns one of 2,3,4 (here 2).
1 <= nums.length <= 2 * 10^4-2^31 <= nums[i] <= 2^31 - 1target is an integer that exists in numsAt most 10^4 calls to pick