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 - Hash Map Preprocessing INPUT nums array: 1 i=0 2 i=1 3 i=2 3 i=3 3 i=4 target = 3 3 Input Values nums = [1,2,3,3,3] target = 3 Find random index where nums[i] == 3 ALGORITHM STEPS 1 Build HashMap Map value to indices list 2 Store Indices Group all indices by value 3 Look up Target Get indices list for target 4 Random Select Pick random from list HashMap Structure Key Indices 1 --> [0] 2 --> [1] 3 --> [2, 3, 4] FINAL RESULT Valid indices for target=3: 2 3 4 Equal probability: 1/3 each Random Pick Output pick(3) returns One of: 2, 3, or 4 OK - Uniform distribution Key Insight: HashMap preprocessing allows O(1) lookup for all indices of a target value. By storing indices in a list, we can pick randomly with uniform probability using random.choice(). Time: O(n) preprocessing, O(1) pick | Space: O(n) for the HashMap storage. TutorialsPoint - Random Pick Index | Hash Map Preprocessing Approach
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