Example 1
- Input
- Solution([1,2,3]); getRandom()
- Output
- 1 (one possible result)
With controlled integer draws 1,2,2 from ranges [1,1],[1,2],[1,3], only node 1 replaces the candidate. Values 1,2,3 each have probability 1/3.
Choose a uniformly random node from a singly linked list using Reservoir Sampling. Keep one candidate and scan the list without storing all nodes.
Implement Solution(head) and getRandom(). Each call returns a node value, and every node must have equal selection probability. Duplicate values remain distinct node outcomes. The official exercise provides a nonempty list and asks how to handle unknown length without extra storage. Each snippet expects the judge’s ListNode with fields val and next. The list remains unchanged during sampling. Random transcripts are possible outcomes, not fixed required outputs.
1 <= node count <= 10^4.-10^4 <= Node.val <= 10^4.10^4 calls to getRandom.With controlled integer draws 1,2,2 from ranges [1,1],[1,2],[1,3], only node 1 replaces the candidate. Values 1,2,3 each have probability 1/3.
The sole node replaces the candidate with probability one, so every call returns -4.
Each node is selected with probability 1/3. The two distinct nodes with value 7 contribute separate equal shares to that value’s probability.
This is the official example’s possible sequence, excluding the null constructor result. All calls scan anew and each may return any of the three values.
Maintain a reservoir of one node. On visiting node i, replace the current candidate with probability 1/i. Early nodes have more chances to be evicted, balancing their earlier selection. For Example 1, choose node 1 automatically, keep it at node 2 with probability 1/2, and keep it at node 3 with probability 2/3: node 1 survives with probability 1/3. Nodes 2 and 3 also finish with probability 1/3. Store the head and restart the scan on every call, so repeated samples do not require a value array.
Reveal Reservoir Sampling: intuition, complexity, and code
Reservoir Sampling maintains a uniform sample as an unknown-length stream grows. Its correctness comes from selection and survival probabilities, and its constant memory trades away constant-time resampling.