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
Random Pick with Weight INPUT Weight Array w = [1, 3] 1 i=0 3 i=1 Weight Distribution: w[0]=1 w[1]=3 Total Sum = 1 + 3 = 4 P(0)=25%, P(1)=75% ALGORITHM STEPS 1 Build Prefix Sum prefix = [1, 4] 1 4 2 Generate Random rand in [1, sum] rand in [1, 4] 3 Binary Search Find first prefix[i] >= rand value 4 Return Index rand=1 --> return 0 rand=2,3,4 --> return 1 0 1 4 i=0 i=1 FINAL RESULT pickIndex() returns: 0 or 1 25% chance 75% chance 75% 25% Index 0 (25%) Index 1 (75%) OK - Weighted Random! Key Insight: Convert weights to prefix sums creating ranges. A random number in [1, total_sum] maps to an index via binary search. Larger weights create larger ranges, thus higher probability of selection. Time: O(n) init, O(log n) pick | Space: O(n) for prefix sum array TutorialsPoint - Random Pick with Weight | Optimal Solution (Prefix Sum + Binary Search)
Asked in
Facebook 35 Google 28 Amazon 22 Microsoft 18
156.0K Views
Medium Frequency
~25 min Avg. Time
1.9K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen