Math Fundamentals18 sections · 814 units
Open in Course

Weighted Pick - Binary Search

Finding the target range

Once you have the prefix sum array and a random number rr, you need to find the smallest index ii where prefix[i]rprefix[i] \geq r.

This is a classic binary search pattern. The prefix sum array is sorted, so binary search runs in O(logn)O(\log n) time.

Why does this give correct probabilities? Because each index owns a range proportional to its weight, and you pick uniformly from all ranges combined.