Random Pick with Weight
MediumArray
Description
Given array w where w[i] is the weight of index i, randomly pick an index with probability proportional to its weight. Return any valid picked index as an integer.
Examples
Input:
w = [1,3]Output:
0 or 1Explanation:
Both indices can be returned. Index 1 has weight 3 while index 0 has weight 1, so index 1 is chosen more often across many calls.
Input:
w = [1]Output:
0Explanation:
Edge case with a single-element array.
Input:
w = [2,1,3,4]Output:
0, 1, 2, or 3Explanation:
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⁴