NeetCode #291LC-528MediumBinary Search
← Back to All Problems#291 · #528 · Random Pick with Weight(按权重随机选择)
📌 Problem Statement & Constraints
You are given a 0-indexed array of positive integers
w where w[i] describes the weight of index i. Implement pickIndex() which returns an index chosen at random with probability proportional to its weight. Constraints: 1 <= w.length <= 10^4, 1 <= w[i] <= 10^5; at most 10^4 calls.💡 Core Algorithmic Approaches
- Build a prefix-sum array of the weights. The total sum defines the sample space.
- Draw a uniform random integer in
[1, total]and binary search for the first prefix sum that is at least it. - The width of each index's interval in the prefix sums is exactly its weight, which gives the required proportionality.
- Using
bisect_lefton the prefix array is O(log n) per call.
💻 Benchmark Python3 Implementation
class Solution:
def __init__(self, w: List[int]):
from bisect import bisect_left
self.prefix = []
cur = 0
for x in w:
cur += x
self.prefix.append(cur) # cumulative weights
self.total = cur
def pickIndex(self) -> int:
import random
from bisect import bisect_left
target = random.randint(1, self.total) # uniform in [1, total]
return bisect_left(self.prefix, target) # first prefix >= target⚡ Complexity Deep Dive
⏱️ Time Complexity
O(n) preprocessing, O(log n) per pick.
💾 Space Complexity
O(n) for the prefix array.
⚠️ Interview Pitfalls & Follow-ups
- Drawing
random.random() * totaland usingbisect_left: the half-open interval handling is easy to get wrong; a uniform integer in[1, total]withbisect_leftis exact. - Using
random.randint(0, total): the value 0 has no corresponding interval and would return index 0 spuriously. - Linear scanning of the prefix array: O(n) per pick.
- Normalising the weights to probabilities first: unnecessary and introduces floating-point error.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
🧩 Related Binary Search Problems
中文速览与面试要点
按权重随机选择
给你一个下标从 0 开始的 正整数 数组 w,其中 w[i] 代表下标 i 的权重。请实现一个函数 pickIndex() ,它可以 随机 地选取并返回下标 i,选取下标 i 的概率为 w[i] / sum(w) 。换句话说,选取下标 i 的概率为 w[i] / sum(w) 。约束:1 ≤ w.length ≤ 10^4;1 ≤ w[i] ≤ 10^5;最多调用 10^4 次 pickIndex。
核心要点
- 前缀和 + 二分(标准解) :构造权重的前缀和数组 prefix ,其中 prefix[i] = w[0] + ... + w[i] 。
- 随机取点 :每次调用时随机生成 target = randint(1, prefix[-1]) ,表示在长度为 sum(w) 的数轴上均匀取一点。
- 二分定位 :用 bisect_left(prefix, target) 找到第一个 prefix[i] >= target 的下标 i,返回 i。
- 为什么这样能得到正确的概率 :下标 i 对应的数轴区间长度恰好为 w[i] ,均匀取点落在该区间的概率即为 w[i] / sum(w) 。
常见陷阱
- 随机范围写成 randint(0, prefix[-1] − 1) :会改变各下标的概率分布。必须用 [1, prefix[-1]] 配合 bisect_left (这是标准的「区间映射」写法)。
- 用 bisect_right :会导致边界点被映射到错误的下标(虽然概率误差极小,但严格来说不正确)。必须用 bisect_left 。
- 每次调用重新计算前缀和 :O(n) 让单次调用退化为 O(n)。必须在构造函数中预处理。
- 用 random.choices(range(n), weights=w) :Python 标准库确实支持,但每次调用会重新计算累积分布(O(n));且面试中通常要求手写。
参考实现
import random
from bisect import bisect_left
class Solution:
def __init__(self, w: list[int]):
self.prefix = []
cur = 0
for x in w:
cur += x
self.prefix.append(cur) # 前缀和(严格递增,因为 w[i] >= 1)
def pickIndex(self) -> int:
# 在 [1, prefix[-1]] 上均匀取点
target = random.randint(1, self.prefix[-1])
return bisect_left(self.prefix, target)