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 i's, then each index should have an equal probability of returning.Example 1:
Input ["Solution", "pick", "pick", "pick"] [[[1, 2, 3, 3, 3]], [3], [1], [3]] Output [null, 4, 0, 2] Explanation Solution solution = new Solution([1, 2, 3, 3, 3]); solution.pick(3); // It should return either index 2, 3, or 4 randomly. Each index should have equal probability of returning. solution.pick(1); // It should return 0. Since in the array only nums[0] is equal to 1. solution.pick(3); // It should return either index 2, 3, or 4 randomly. Each index should have equal probability of returning.
Constraints:
1 <= nums.length <= 2 * 104
-231 <= nums[i] <= 231 - 1
target
is an integer from nums
.104
calls will be made to pick
.When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:
The brute force method for this problem is straightforward. We will look through the entire collection of numbers every time we need to pick a random spot where our special number is located. This approach guarantees we find a suitable position if it exists.
Here's how the algorithm would work step-by-step:
import random
class Solution:
def __init__(self, numbers):
self.numbers = numbers
def pick(self, target):
# Find all indices where the number appears
target_indices = []
for index in range(len(self.numbers)):
if self.numbers[index] == target:
# Remember this index because value matches.
target_indices.append(index)
# Choose a random index from available indices
chosen_index = random.choice(target_indices)
return chosen_index
The challenge is to pick a random spot that contains a specific value. We don't want to store every location of the value because that would take too much space. Instead, we'll use a clever trick to pick a random spot on-the-fly as we look at the input.
Here's how the algorithm would work step-by-step:
import random
class Solution:
def __init__(self, numbers):
self.numbers = numbers
def pick(self, target):
chosen_index = -1
occurrence_count = 0
for index, number in enumerate(self.numbers):
if number == target:
occurrence_count += 1
# Reservoir sampling: replace existing choice with
# probability 1/occurrence_count
if random.randint(1, occurrence_count) == 1:
chosen_index = index
return chosen_index
Case | How to Handle |
---|---|
Null or empty input array | Return -1 immediately as there are no possible indices to pick from. |
Array with only one element | Always return 0 as the only available index when the target matches this single element. |
Large array size (scalability) | Use Reservoir Sampling for efficiency to avoid storing all indices in memory. |
Target value not present in the array | Return -1, indicating the target was not found in the array. |
Integer overflow when calculating random index | Ensure the random number generation and index calculation are within integer limits or use a larger data type. |
Array contains a large number of occurrences of the target | Reservoir sampling will handle this correctly, giving each occurrence an equal probability of being selected. |
The target value is near the min or max integer value. | No special handling needed, as the algorithm searches directly for the numerical target value. |
Random number generator has poor randomness. | Use a well-established and tested random number generator for even index distribution. |