You are given an array w of positive integers, where w[i] describes the weight of index i.
Write a function pickIndex which randomly picks an index in proportion to its weight.
pickIndex calls after initializing with the array w?
pickIndex may be called multiple times.The problem can be broken down into two main parts:
We’ll calculate a prefix sum of the weights. This will allow us to use binary search to quickly determine the correct index for a given pick.
To pick an index, we:
bisect in Python) to find the first prefix sum that is greater than or equal to the random number.import random
import bisect
class Solution:
def __init__(self, w):
self.prefix_sums = []
self.total_sum = 0
for weight in w:
self.total_sum += weight
self.prefix_sums.append(self.total_sum)
def pickIndex(self):
target = random.randint(1, self.total_sum)
index = bisect.bisect_left(self.prefix_sums, target)
return index
__init__ method):
self.prefix_sums stores the accumulated sums of weights. For example, if w = [1, 3, 2], the prefix_sums will be [1, 4, 6].self.total_sum is the total of all weights; here it would be 6.pickIndex method):
1 and self.total_sum. This corresponds to randomly selecting a point on the cumulative weight scale.bisect.bisect_left to find the first index in the prefix_sums where the cumulative sum is greater than or equal to the random number.This approach ensures that indices with larger weights have a proportionally higher chance of being picked, as required by the problem statement.
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?