Problem Description
Initialize the object with an integer array nums (which may contain duplicates) and implement the method pick(target) that randomly returns an index i from nums such that nums[i] == target. Each valid index for a target must have equal probability of being returned.
Key Insights
- Reservoir sampling is used to select a random index without using extra space for storing indices.
- During a single pass over the array, you can decide probabilistically whether to choose the current valid index.
- Consistent probability handling ensures each target occurrence is equally likely.
- This approach avoids preprocessing, keeping space usage minimal.
Space and Time Complexity
Time Complexity: O(n) per pick call, where n is the length of the nums array. Space Complexity: O(1) extra space (apart from storing the input array).
Solution
We leverage the reservoir sampling algorithm for each pick call. When the pick method is called with a target value:
- Initialize a counter (found) to track the number of target occurrences.
- Iterate over the nums array.
- Each time the target is found, increment the counter.
- With probability 1/found, replace the result with the current index.
- Return the final selected index.
This method ensures that when multiple valid indices exist, each one is chosen with the same probability.