The "Linked List Random Node interview question" asks you to return a random node's value from a linked list. Every node must have an equal probability of being chosen. The catch? The list could be extremely large, and you might not know its length in advance. This "Linked List Random Node coding problem" is a classic application of a specific sampling algorithm.
Companies like Meta and Google ask this to test your knowledge of the "Reservoir Sampling interview pattern". It evaluates whether you can solve a problem with space constraints—specifically, finding a random element in a single pass without storing the entire list in memory.
The Reservoir Sampling pattern is used here. You initialize your "result" with the value of the head node. As you iterate through the list at index i (starting from 0), you generate a random number between 0 and i. If that random number is 0, you replace your "result" with the current node's value. By the time you reach the end of the list, each node will have had a 1/n probability of being the final result.
List: 10 -> 20 -> 30
Reservoir sampling is the standard answer for "random selection from a stream." Memorize the logic: for the i-th element, replace the current choice with probability 1/(i+1).
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Random Pick Index | Medium | Solve | |
| Random Flip Matrix | Medium | Solve | |
| Plus One Linked List | Medium | Solve | |
| Convert Binary Number in a Linked List to Integer | Easy | Solve | |
| Double a Number Represented as a Linked List | Medium | Solve |