Leetcode 398. Random Pick Index
You are given an integer array nums
with possible duplicates. You want to design an algorithm that randomly picks an index of a given target number. 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, each index should have an equal probability of being returned.nums
array?
nums
will have a length of up to 50,000.nums
can be between -1,000,000 and 1,000,000.pick
function be called relative to the initialization?
pick
function may be called multiple times after the Solution
object is initialized.pick
function should be optimized for efficiency, ideally constant time.To solve this problem, we’ll use Reservoir Sampling, a technique used to randomly choose k samples from a list of n items, where n is either a very large or unknown number.
Solution
constructor):
nums
.pick
function):
Explanation of Reservoir Sampling for this problem:
nums
. For each index i
where nums[i]
equals the target
, choose that index with a certain probability.This ensures that each valid index has an equal probability of being chosen.
#include <vector>
#include <cstdlib>
#include <ctime>
class Solution {
private:
std::vector<int> nums;
public:
Solution(std::vector<int>& nums) {
this->nums = nums;
std::srand(std::time(0)); // Initialize random number generator
}
int pick(int target) {
int chosen_index = -1;
int count = 0;
for (int i = 0; i < nums.size(); ++i) {
if (nums[i] == target) {
++count;
if (std::rand() % count == 0) { // Probability of 1/count
chosen_index = i;
}
}
}
return chosen_index;
}
};
O(n)
where n
is the length of the nums
array.
pick
function runs in O(n)
where n
is the length of the nums
array.pick
function, although it has linear time complexity with respect to the size of the input array, is optimized for scenarios with multiple valid targets.Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?