Math Fundamentals18 sections · 814 units
Open in Course

Linked List Random Node - Insight

Reservoir sampling idea

As you traverse, keep a current selection. For the ii-th node, replace your selection with probability 1/i1/i. After seeing all nn nodes, each has probability 1/n1/n of being selected.

Why does this work? Node 1 is kept with probability 1×(11/2)×(11/3)×...×(11/n)=1/n1 \times (1 - 1/2) \times (1 - 1/3) \times ... \times (1 - 1/n) = 1/n. The same holds for all other nodes by similar calculation.