Description

Given array w where w[i] is weight of index i, randomly pick an index with probability proportional to weight.

Examples

Input:w = [1,3]
Output:index 1 with probability 3/4
Explanation:

Weight-based random selection.

Input:w = [1]
Output:index 1 with probability 3/4
Explanation:

Edge case with a single-element array.

Input:w = [2,1,3,4]
Output:index 3 with probability 4/10 = 2/5
Explanation:

Total weight is 2+1+3+4=10. Index 0 has probability 2/10, index 1 has 1/10, index 2 has 3/10, and index 3 has the highest probability at 4/10. This demonstrates how larger weights correspond to higher selection probabilities in a multi-element array.

Constraints

  • 1 ≤ w.length ≤ 10⁴

Ready to solve this problem?

Practice solo or challenge other developers in a real-time coding battle!