The Random Pick with Weight problem asks you to design a class that randomly picks an index with probability proportional to its weight. If weights=[3,1], index 0 should be picked 75% of the time and index 1 25% of the time. This coding problem uses prefix sums with binary search for weighted random sampling. The array, math, binary search, randomized, and prefix sum interview pattern is the core.
Apple, Uber, Microsoft, Meta, Amazon, Google, Bloomberg, and Adobe ask this because weighted random sampling is fundamental to machine learning (sampling proportional to importance), load balancing, A/B testing, and recommendation systems. The prefix sum + binary search approach is clean and efficient.
Prefix sums + binary search. Build prefix sum array from weights. Total = prefix[-1]. For each pick: generate random number r in [1, total]. Binary search in prefix array for the leftmost position where prefix[i] >= r. Return that index.
weights=[3,1,2]. Prefix=[3,4,6]. Total=6.
Random Pick with Weight is the canonical weighted sampling problem. The prefix sum creates "weight intervals" on [1, total]; binary search finds which interval a random number falls into. Practice: "weighted random shuffle," "probabilistic load balancer," "roulette wheel selection." The prefix sum + bisect_left pattern is the standard implementation — memorize it.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Random Point in Non-overlapping Rectangles | Medium | Solve | |
| Special Array II | Medium | Solve | |
| Sum of Absolute Differences in a Sorted Array | Medium | Solve | |
| Zero Array Transformation II | Medium | Solve | |
| Maximum Number of Upgradable Servers | Medium | Solve |