Random Pick with Weight
Given an array w of positive integer weights, implement pickIndex() that returns index i with probability w[i] divided by the sum of all weights.
Open official problem prompt ↗Choose an index at random so that each index's chance is proportional to its weight, efficiently over many queries.
A raffle where index i gets w[i] tickets in one big drum; you draw a single ticket number and see which index's block of tickets it falls into.
- Input
- w = [1,3]; call pickIndex() repeatedly
- Output
- [1]
- Why
- Index 0 is returned with probability 1/4 and index 1 with probability 3/4; a single call here returned 1, its more likely outcome.
1 <= w.length <= 10^41 <= w[i] <= 10^5pickIndex will be called at most 10^4 times