Skip to content

Practice Random Pick Index

Read the task, work through the examples, and check your approach against the constraints. Use the original LeetCode task for coding and submissions.

Medium#398
LeetCode Problem

Random Pick Index

Problem Statement

Solution(nums) stores an array that may contain duplicates. pick(target) returns a uniformly chosen zero-based index containing target; the target is guaranteed to occur. Practice approach: Precompute an index list for each value, then sample uniformly from the matching list. Alternatively, reservoir-sample only matching indices during a scan to avoid index-list storage. Sampling a distinct value first would solve a different problem: the selection must be among occurrences of the specified target.

Source: Random Pick Index on LeetCode. Use the original task for its coding environment and submissions.

Examples

# Example 1

Input
["Solution","pick","pick","pick"]
[[[4,7,7,9]],[7],[4],[7]]
Output
[null,2,0,1]
Explanation

Indices 1 and 2 are equally likely for target 7; the unique index for target 4 is always zero. The displayed random choices are one possible sequence.

Constraints

1 <= nums.length <= 2 * 10^4
-2^31 <= nums[i] <= 2^31 - 1
Every target occurs in nums.
At most 10^4 pick calls.

Related LeetCode Problems

Practice more problems similar to Random Pick Index.

Review your practice with PhantomCodeAI

After trying the problem yourself, use the app to discuss your approach, complexity, and edge cases.