Medium · System Design

Random Pick with Weight

Given an array w of positive integers, implement pickIndex(), which returns a random index i in [0, w.length) with probability w[i] / sum(w).

Examples

Example 1

{
  "weights": [1, 3],
  "targets": [1, 4]
}

Output: [0, 1]

Example 2

weights=[2,5,3], tickets=[1,2,3,7,8,10]

Output: [0, 0, 1, 1, 2, 2]

Rebuild it in the studio

Open every published interview problem, solution, scene, and memory room free, with no account.

More System Design problems