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 array nums.
  • int pick(int target) Picks a random index i from nums where nums[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
Random Pick Index: Find target=3 in [1,2,3,3,3]1233301234Valid indices: [2, 3, 4]🎲 Random PickOutput: 2, 3, or 4 (each with 1/3 probability)
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
Asked in
Facebook 35 Google 28 Amazon 22 Microsoft 18
64.5K Views
Medium Frequency
~15 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen