Math Fundamentals18 sections · 814 units
Open in Course

Weighted Pick - Prefix Sum

Converting weights to ranges

The key insight: convert weights into cumulative ranges, then pick a random number in the total range.

For weights [1,3,2][1, 3, 2], build prefix sums [1,4,6][1, 4, 6]. Index 00 owns range [1,1][1, 1], index 11 owns range [2,4][2, 4], index 22 owns range [5,6][5, 6]. Pick a random number from 11 to 66, then find which range it falls into.

This transforms weighted sampling into a range lookup problem. Binary search finds the range in O(logn)O(\log n) time.