LeetCode 528. Random Pick with Weight
Question
You are given a 0-indexed array of positive integers w
where w[i]
describes the weight of the ith
index.
You need to implement the function pickIndex()
, which randomly picks an index in the range [0, w.length - 1]
(inclusive) and returns it. The probability of picking an index i
is w[i] / sum(w)
.
- For example, if
w = [1, 3]
, the probability of picking index0
is1 / (1 + 3) = 0.25
(i.e.,25%
), and the probability of picking index1
is3 / (1 + 3) = 0.75
(i.e.,75%
).
Constraints:
1 <= w.length <= 104
1 <= w[i] <= 105
pickIndex
will be called at most104
times.
Source: https://leetcode.com/problems/random-pick-with-weight/
Solution
In theory, we create several intervals from the weight array. Then generate a random value. In which interval the random value falls, the corresponding index is returned.
The key point is how to determine which interval the random value falls. We use binary search so that the time complexity is O(log(n))
. In Java, TreeMap
is implemented based on Red-Black tree, a kind of self-balancing binary search tree. Thus, we can also use TreeMap
to get the same time complexity.
class RandomPickWithWeight
Use TreeMap
to store lower bounds.
1 | // lower bound -> index |
Use prefix sum and binary search. Prefix sum array represents upper bounds.
1 | private Random rand; |
LeetCode 528. Random Pick with Weight
http://yenotes.org/2022/03/09/LeetCode-528-Random-Pick-with-Weight/