Random Pick with Weight - Problem
You are given a 0-indexed array of positive integers w where w[i] describes the weight of the ith index.
You need to implement the function pickIndex(), which randomly picks an index in the range [0, w.length - 1] (inclusive) and returns it. The probability of picking an index i is w[i] / sum(w).
For example, if w = [1, 3], the probability of picking index 0 is 1 / (1 + 3) = 0.25 (i.e., 25%), and the probability of picking index 1 is 3 / (1 + 3) = 0.75 (i.e., 75%).
Input & Output
Example 1 — Basic Weighted Selection
$
Input:
w = [1,3]
›
Output:
0 or 1 (with probabilities 25% and 75%)
💡 Note:
Index 0 has weight 1, index 1 has weight 3. Total sum is 4. Random number 1 maps to index 0, numbers 2-4 map to index 1.
Example 2 — Equal Weights
$
Input:
w = [2,2,2]
›
Output:
0, 1, or 2 (each with 33.33% probability)
💡 Note:
All indices have equal weight 2. Total sum is 6. Numbers 1-2 → index 0, 3-4 → index 1, 5-6 → index 2.
Example 3 — Single Element
$
Input:
w = [5]
›
Output:
0 (100% probability)
💡 Note:
Only one index available, so it's always selected regardless of weight value.
Constraints
- 1 ≤ w.length ≤ 104
- 1 ≤ w[i] ≤ 105
- pickIndex will be called at most 104 times
Visualization
Tap to expand
Understanding the Visualization
1
Input Weights
Array [1,3,2] represents relative weights for each index
2
Build Ranges
Convert to cumulative ranges: [1,4,6] for probability mapping
3
Random Pick
Generate random number and find which range it falls into
Key Takeaway
🎯 Key Insight: Transform weights into cumulative probability ranges, then binary search for O(log n) random selection
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code