Given a singly linked list, getRandom() returns the value of a node chosen uniformly at random. Solve the follow-up: the list may be extremely long and its length is unknown, so don't store the nodes or count them first.
Before you code
When you reach the i-th node, you don't know how many nodes follow. With what probability should it become the current choice so that every node seen so far is equally likely?
Hints
- Walk the list, keeping one chosen value.
- At the i-th node, counting from 1, replace the chosen value with probability 1/i, for example when randint(1, i) == 1.
- Prove it: an earlier node chosen with probability 1/(i − 1) survives step i with probability 1 − 1/i, giving 1/i.
Production & complexity notes
When solving Linked list random node on LeetCode (medium), always state your loop or recursion invariant before writing code. Verify how your chosen data structure behaves on degenerate inputs (single-element inputs, all-duplicate keys, strictly monotonic sequences, or maximum constraint sizes up to $10^5$ elements). In production interviews, pair your implementation with an explicit time and auxiliary space complexity proof, explain why alternative brute-force approaches violate the latency budget, and trace how cache locality and memory allocation overhead affect wall-clock throughput on real hardware. Review the step-by-step memory trace in Randomized algorithms to reinforce the underlying pattern.
What it practices
Reservoir sampling, from Randomized algorithms.