You are given an array w of positive whole numbers: w[i] is the weight of index i. Build a class that is created with w and has one method, pickIndex().
Each call to pickIndex() returns one index at random, where index i comes up with chance w[i] divided by the sum of all weights. A weight twice as big means the index is picked twice as often.
Example 1
Input: Solution([2, 5, 1, 4]), then pickIndex() three times Output: three random indices, e.g. 1, 3, 1 Why: index 1 has 5 of the 12 units of weight, so 5/12 of picks
2 more examples and the constraints
Example 2
Input: Solution([3, 1]), then pickIndex() twice Output: e.g. 0, 0 Why: index 0 comes up 3 times in 4, index 1 once in 4
Example 3
Input: Solution([9]), then pickIndex() Output: 0 Why: there is only one index to pick
Constraints
- 1 ≤ length of w ≤ 10,000
- 1 ≤ w[i] ≤ 100,000
- pickIndex() is called at most 10,000 times
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Prefix sums + linear scanO(n) per pick
- Prefix sums + binary searchO(log n) per pick
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 10,000 weights and 10,000 picks | Verdict |
|---|---|---|---|
| Prefix sums + linear scan | O(n) per pick | Mention it, then move on | |
| Prefix sums + binary search | O(log n) per pick | Best; log n per pick |
n = length of w.
Edge cases to test
- One weight. Solution([9]) must always return 0.
- Equal weights. Every index should come up equally often.
- One huge weight. With [1, 100000], index 0 is picked about once in 100,001 calls, but it must still be possible.
- Largest total. 10,000 weights of 100,000 sum to 1,000,000,000, which still fits a 32-bit int.
- Target on a boundary. A target equal to prefix[i] belongs to index i, not i + 1.
Common mistakes
- Drawing the target from 0 to total − 1 but still searching for the first prefix ≥ target, so index 0 gets one unit too many.
- Rebuilding the prefix sums inside pickIndex, which makes every pick O(n).
- Picking an index uniformly, ignoring the weights.
How to talk through it
- 1Clarify. Are all weights positive? How many picks will there be compared with the length of w?
- 2Draw the number line. Each index owns a block as long as its weight; a uniform point on the line picks by weight.
- 3Give the scan. Prefix sums and a left-to-right walk: O(n) per pick, too slow with 10,000 picks.
- 4Binary search the sums. They are sorted, so find the first prefix ≥ target in O(log n).
- 5Test out loud. Walk a target that lands exactly on a boundary, and the single-weight case.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?