Random Pick Index - Problem
Given an integer array nums with possible duplicates, randomly output the index of a given target number. You can assume that the given target number must exist in the array.
Implement the Solution class:
Solution(int[] nums)Initializes the object with the arraynums.int pick(int target)Picks a random indexifromnumswherenums[i] == target. If there are multiple valid indices, then each index should have an equal probability of returning.
Input & Output
Example 1 — Basic Case
$
Input:
nums = [1,2,3,3,3], target = 3
›
Output:
One of [2,3,4]
💡 Note:
Target 3 appears at indices 2, 3, 4. Each index should be returned with equal 1/3 probability
Example 2 — Single Occurrence
$
Input:
nums = [1,2,3,3,3], target = 1
›
Output:
0
💡 Note:
Target 1 appears only at index 0, so we must return 0
Example 3 — Multiple Duplicates
$
Input:
nums = [1,1,1,1,1], target = 1
›
Output:
One of [0,1,2,3,4]
💡 Note:
Target 1 appears at all indices. Each index should be returned with equal 1/5 probability
Constraints
- 1 ≤ nums.length ≤ 2×104
- -231 ≤ nums[i] ≤ 231 - 1
- target is guaranteed to exist in nums
Visualization
Tap to expand
Understanding the Visualization
1
Input
Array [1,2,3,3,3] with target=3
2
Find Matches
Locate all indices where nums[i] == target
3
Random Pick
Select one index with equal probability
Key Takeaway
🎯 Key Insight: Multiple approaches exist, from simple linear scan to elegant reservoir sampling, each with different time-space tradeoffs
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code