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: [1,3,2]132Index 0Index 1Index 212,3,45,616.7%50.0%33.3%Random number 1-6 → Index with higher weight more likely selectedUse prefix sums [1,4,6] and binary search for efficient O(log n) lookup
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
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