Build a class Solution. Its constructor receives an array of integers, nums, which may contain repeats. Its method pick(target) returns an index i with nums[i] == target.
When the target appears at several indices, each of them must be returned with the same probability. The target passed to pick is always somewhere in the array.
Example 1
Input: Solution([5, 8, 5, 2, 5]), then pick(5), pick(8), pick(5) Output: one of 0, 2, 4; then 1; then one of 0, 2, 4 Why: 5 sits at indices 0, 2 and 4; 8 only at 1
2 more examples and the constraints
Example 2
Input: Solution([7]), then pick(7) Output: 0 Why: one number, one possible index
Example 3
Input: Solution([-1, -1, 4]), then pick(-1), pick(4) Output: 0 or 1, each half the time; then 2 Why: -1 appears twice, 4 once
Constraints
- 1 ≤ length of nums ≤ 20,000
- Each nums[i] fits in a signed 32-bit integer
- target always occurs in nums
- pick 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.
- Map of positionsO(1) per pick
- Reservoir samplingO(n) per pick
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Extra memory for 20,000 numbers | Verdict |
|---|---|---|---|
| Map of positions | O(1) per pick | Fast picks; stores every index | |
| Reservoir sampling | O(n) per pick | Best on memory; one scan a pick |
n = length of nums. The bars compare extra memory, not time.
Edge cases to test
- One occurrence. The only matching index must come back every time.
- Every number is the target. [3, 3, 3, 3, 3, 3]: each index should come back about a sixth of the time.
- Extreme values. −2,147,483,648 and 2,147,483,647 work as map keys and in comparisons; no arithmetic is done on them.
- Many calls. Up to 10,000 picks: the map answers each in O(1); reservoir pays a full scan each time.
Common mistakes
- Replacing the choice with probability 1/2 at every match, which favours the last indices.
- Counting from 0 so the first match divides by zero, or rolling
randrange(count + 1). - Shuffling or sorting
nums, which loses the original indices.
How to talk through it
- 1Clarify. Is the target always present? How many picks, and how big can the array be? Is memory tight?
- 2Give the map. Value to list of indices; pick a random entry. O(1) per pick, O(n) memory.
- 3Answer the memory follow-up. Reservoir sampling: keep the k-th match with chance 1/k.
- 4Prove it is fair. Chosen at k, then kept by every later match: the product is 1/c for each index.
- 5Test out loud. Run a target that appears once and one that fills the array.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?