2dbi
Home/Meta/Random Pick with Weight
MMeta·DSAE5Onsite – Coding 2

Random Pick with Weight

Problem

Given an array w of positive weights, implement pickIndex() that returns index i with probability proportional to w[i].

Example

w = [1,3] -> index 0 ~25%, index 1 ~75%

Constraints

  • 1 ≤ w.length ≤ 10^4

Approach

Prefix sums + binary search on a random target in [1, total]. Classic Meta question.

added 6 days ago
LeadersAccount