TRT
Sign in
mediumExpertLeetCode#reservoir sampling

Linked list random node

Pick a uniformly random node from a linked list in one pass with O(1) extra memory, using reservoir sampling.

The Runtime Theory Team1 min read
Taught inRandomized algorithmsPro — members onlyRandomized algorithms flip coins to escape bad inputs, sample fairly, or answer quickly with a small chance of error. Analyzing them means computing expected costs and error probabilities that hold for every input.
Solve it

Solving happens on the judge — come back and mark it done

Sample cases

inhead = [1, 2, 3], getRandom() called many times

outeach of 1, 2 and 3 about one third of the time

inhead = [10], getRandom()

out10

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

  1. Walk the list, keeping one chosen value.
  2. At the i-th node, counting from 1, replace the chosen value with probability 1/i, for example when randint(1, i) == 1.
  3. 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.

Not started

Sign in to save your learning progress.

Sign in to save