Uniformly Sample K Customer Reviews From a Stream of Unknown Length
Last updated: November 29, 2026
Quick Overview
Reviews stream in and the total count is not known in advance. Maintain a sample of k reviews such that, at any point, every review seen so far has equal probability of being in the sample, using O(k) memory.
Amazon
November 29, 20260
0
0 solved
Reviews stream in and the total count is not known in advance. Maintain a sample of k reviews such that, at any point, every review seen so far has equal probability of being in the sample, using O(k) memory.
Review quality audits at Amazon need unbiased samples from feeds too large to store. The interviewer checks that you know reservoir sampling, can prove its uniformity, and can extend it to weighted or distributed settings.
What the Interviewer Expects
- Fill the reservoir with the first k items
- For item i (1-indexed, i > k) replace a random slot with probability k / i
- Prove each item ends up in the sample with probability k / n
- O(1) time per item and O(k) space
- Discuss seeding and reproducibility for audits
Key Topics to Cover
How to Approach This
- Clarify input constraints and edge cases before writing code.
- Walk through your approach verbally and confirm with the interviewer before coding.
- Start with a brute force solution, then optimize. Mention time and space complexity.
- Test your solution with examples, including edge cases like empty input or duplicates.
- Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
- How would you sample when reviews have weights (for example by helpful votes)?
- How would you combine reservoirs from 100 parallel shards into one uniform sample?
- How would you skip ahead to reduce random number calls on very long streams?
Sharpen Your Skills on Codemia
Practice similar problems with our interactive workspace, get AI feedback, and track your progress.
Practice DSA ProblemsSample Answer
Requirements
Input: an iterable of reviews of unknown length n and an integer k >= 1. Output: a list of min(k, n) reviews, each review included with probability k / n. Memory must be O(k); the stream can only be r...
High-Level Design
Algorithm R. Keep the first k items. For the i-th item with i > k, draw j uniformly from [0, i). If j < k, overwrite slot j. Proof by induction: item i is chosen with probability k / i, and an item al...