Algorithms and Data Structures · Senior · Question 17 of 75

How do you pick a uniformly random sample of k items from a stream of unknown length?

Explanation

After any number of items each one is in the reservoir with equal probability k/n, using O(k) memory and one pass. Taking every k-th item isn't uniform and depends on the stream length.

Further reading

Problem with a question

Algorithms and Data Structures · Senior · question 17

Test yourself

Take the Algorithms and Data Structures · Senior quiz: questions and options are shuffled, and you get a review of your mistakes at the end.

Take this quiz