AdvancedMath for DSALinked List

Picking at random fairly: reservoir sampling

Don't know the length? Keep the i-th item with probability 1/i. Every item ends up chosen with exactly 1/n chance, in one pass.

The idea

To pick uniformly from a stream (or a you can't index), keep a current choice. When you see the i-th item, replace the choice with probability 1/i.

Why it's fair: item i is picked at step i with chance 1/i, then survives each later step j with chance (1 − 1/j). Multiply: 1/i × i/(i+1) × … × (n−1)/n = 1/n. The same “each one equally likely” thinking underlies a correct shuffle (Fisher–Yates).

Worked example

Stream a, b, c

  1. a: keep with 1/1 → choice a.
  2. b: replace with 1/2 → a or b, each 1/2.
  3. c: replace with 1/3 → c is 1/3; a and b each 1/2 × 2/3 = 1/3.

Pseudocode

The steps in plain words. ← means “set to”; indentation shows what's inside what.

reservoir sampling (one item, unknown length):
choice ← none, i ← 0
for each item:
i ← i + 1
with probability 1/i: choice ← item
return choice(each item: probability 1/n)
shuffle (Fisher–Yates):
for i from the last index down to 1:
j ← random index from 0 to i
swap nums[i], nums[j]

See it run

The worked example, step by step, beside the Python. The highlighted line is the one running.

Step-by-step

a stream: a, b, c

stream

0a
1b
2c

Solution · Pythonline 4

import random
def pick_random(head): # Linked List Random Node
choice, i, node = None, 0, head
while node:
i += 1
if random.randrange(i) == 0: # probability 1/i
choice = node.val
node = node.next
return choice
def shuffle(nums): # Fisher–Yates
for i in range(len(nums) - 1, 0, -1):
j = random.randint(0, i)
nums[i], nums[j] = nums[j], nums[i]
return nums

Step 1 of 5· line 4

Pick one item fairly without knowing how many will come. When item i arrives, take it with probability 1/i. Every item ends up equally likely.

time, space.

How to spot it

  • “random / index with equal probability”, unknown or huge input length, “shuffle”.

Common mistakes

  • Shuffling with j from the whole array each time: it looks random but isn't uniform.
  • Counting the length first when one pass is enough.

Practise the ideas first

Where it comes up

Go further