Practice Random Pick with Weight
Read the task, work through the examples, and check your approach against the constraints. Use the original LeetCode task for coding and submissions.
Problem Statement
Solution(w) stores positive weights. pickIndex() chooses zero-based index i with probability w[i] divided by the total weight. Independent calls may return the same index repeatedly. Practice approach: Build cumulative weights. Draw an integer uniformly from 1 through the total and binary-search the first cumulative weight at least that draw. Each index then owns exactly its weight in possible draws. Check both interval endpoints and use an integer type large enough for the total. Preprocessing is O(n); each pick is O(log n).
Source: Random Pick with Weight on LeetCode. Use the original task for its coding environment and submissions.
Examples
# Example 1
["Solution","pickIndex","pickIndex","pickIndex"] [[[2,3]],[],[],[]]
[null,1,0,1]
One possible sequence is shown. Index zero has probability 2/5 and index one 3/5; the example is not a required sample frequency.
Constraints
Related LeetCode Problems
Practice more problems similar to Random Pick with Weight.
Review your practice with PhantomCodeAI
After trying the problem yourself, use the app to discuss your approach, complexity, and edge cases.