Random Pick with Weight - Problem
Weighted Random Selection
You are given a
You need to implement the function
Example: If
โข Probability of picking index 0 =
โข Probability of picking index 1 =
This means index 1 should be selected 3 times more often than index 0 over many calls to
You are given a
0-indexed array of positive integers w where w[i] describes the weight of the ith index. Your task is to implement a data structure that supports weighted random selection.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 index i should be proportional to its weight: w[i] / sum(w).Example: If
w = [1, 3], then:โข Probability of picking index 0 =
1 / (1 + 3) = 0.25 (25%)โข Probability of picking index 1 =
3 / (1 + 3) = 0.75 (75%)This means index 1 should be selected 3 times more often than index 0 over many calls to
pickIndex(). Input & Output
example_1.py โ Basic Usage
$
Input:
w = [1, 3]
Solution(w)
pickIndex() called multiple times
โบ
Output:
Returns 0 approximately 25% of the time, 1 approximately 75% of the time
๐ก Note:
With weights [1, 3], the total sum is 4. Index 0 has weight 1/4 = 25% probability, index 1 has weight 3/4 = 75% probability.
example_2.py โ Equal Weights
$
Input:
w = [1, 1, 1, 1]
Solution(w)
pickIndex()
โบ
Output:
Each index (0, 1, 2, 3) returned with equal 25% probability
๐ก Note:
When all weights are equal, each index has the same probability of being selected, making it uniform random selection.
example_3.py โ Single Element
$
Input:
w = [5]
Solution(w)
pickIndex()
โบ
Output:
Always returns 0
๐ก Note:
With only one element, there's only one possible index to return, so it's selected with 100% probability.
Visualization
Tap to expand
Understanding the Visualization
1
Create Weighted Dartboard
Each index becomes a sector with size proportional to its weight
2
Build Prefix Sum Boundaries
Calculate cumulative boundaries to know where each sector starts and ends
3
Throw the Dart
Generate a random position on the dartboard
4
Binary Search for Sector
Quickly find which sector the dart landed in using binary search
Key Takeaway
๐ฏ Key Insight: Transform the weighted selection problem into a range lookup problem using prefix sums, then leverage binary search for efficient O(log n) queries!
Time & Space Complexity
Time Complexity
O(n)
Each pickIndex() call requires O(n) time to iterate through weights array
โ Linear Growth
Space Complexity
O(1)
Only using constant extra space for variables
โ Linear Space
Constraints
- 1 โค w.length โค 104
- 1 โค w[i] โค 105
- pickIndex will be called at most 104 times
- All weights are positive integers
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code