Random Pick Index - Problem
Random Pick Index is a fascinating problem that combines data structures with probability theory. You're given an integer array
The challenge lies in ensuring uniform probability - if a target appears multiple times in the array, each occurrence should have an equal chance of being selected. For example, if the number 7 appears at indices [2, 5, 9], then each of these indices should have a 1/3 probability of being returned.
Your mission: Design a
โข
โข
nums that may contain duplicate values, and your task is to implement a class that can randomly select an index for any given target number.The challenge lies in ensuring uniform probability - if a target appears multiple times in the array, each occurrence should have an equal chance of being selected. For example, if the number 7 appears at indices [2, 5, 9], then each of these indices should have a 1/3 probability of being returned.
Your mission: Design a
Solution class with two methods:โข
Solution(int[] nums) - Initialize with the input arrayโข
int pick(int target) - Return a random index where nums[index] == target Input & Output
example_1.py โ Basic Usage
$
Input:
nums = [1,2,3,3,3], target = 3
โบ
Output:
2 or 3 or 4 (each with 1/3 probability)
๐ก Note:
The target 3 appears at indices [2,3,4]. Each index should have equal probability of being returned, so valid outputs are 2, 3, or 4.
example_2.py โ Single Occurrence
$
Input:
nums = [1,2,3,3,3], target = 2
โบ
Output:
1
๐ก Note:
The target 2 appears only at index 1, so we always return 1.
example_3.py โ Multiple Calls
$
Input:
nums = [1,2,3,3,3], multiple pick(3) calls
โบ
Output:
Various combinations of [2,3,4]
๐ก Note:
Over many calls, indices 2, 3, and 4 should each be returned approximately 1/3 of the time, demonstrating uniform random distribution.
Visualization
Tap to expand
Understanding the Visualization
1
Brute Force
Scan entire array each time - Simple but slow O(n) per pick
2
Hash Preprocessing
Build lookup table once - Fast O(1) picks but uses O(n) space
3
Reservoir Sampling
Mathematical elegance - O(1) space with uniform probability guarantee
Key Takeaway
๐ฏ Key Insight: Reservoir sampling achieves the seemingly impossible - uniform random selection from an unknown-size stream using only O(1) space through clever probability mathematics!
Time & Space Complexity
Time Complexity
O(n)
Each pick() requires scanning the entire array once
โ Linear Growth
Space Complexity
O(1)
Only uses a constant amount of extra variables regardless of input size
โ Linear Space
Constraints
- 1 โค nums.length โค 2 ร 104
- -231 โค nums[i] โค 231 - 1
- target is guaranteed to exist in nums
- At most 104 calls will be made to pick
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code