Random Pick with Weight — LeetCode 528 Python Solution
- Problem
- #528
- Pattern
- Prefix Sum
- Reading time
- 4 min
- Source
- leetcode.com
The problem
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.
Example
- Input
- ["Solution","pickIndex"]
- Output
- [null,0]
- Explanation
- Solution solution = new Solution([1]);
Python solution
class Solution:
def __init__(self, w: List[int]):
self.s = [0]
for c in w:
self.s.append(self.s[-1] + c)
def pickIndex(self) -> int:
x = random.randint(1, self.s[-1])
left, right = 1, len(self.s) - 1
while left < right:
mid = (left + right) >> 1
if self.s[mid] >= x:
right = mid
else:
left = mid + 1
return left - 1
# Your Solution object will be instantiated and called as such:
# obj = Solution(w)
# param_1 = obj.pickIndex()Complexity
| Measure | Complexity |
|---|---|
| Time | O(log n) or O(n log n) |
| Space | O(1) auxiliary |
Pattern: Prefix Sum
Precompute running totals once so any range query becomes a single subtraction. LeetCode 528. Random Pick with Weight is filed here because LeetCode tags it Prefix Sum, which is the vocabulary this hub collects.
The prefix sum guide has the Python template for the pattern and the 157 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 528. Random Pick with Weight?
- LeetCode 528. Random Pick with Weight is rated Medium on LeetCode.
- What topics does LeetCode 528. Random Pick with Weight cover?
- LeetCode 528. Random Pick with Weight is tagged Array, Math, Binary Search, Prefix Sum and Randomized on LeetCode.