Sample K Comments Uniformly From a Stream of Unknown Length

Last updated: November 29, 2026

Quick Overview

For quality review, sample exactly k comments uniformly at random from a comment stream whose length is unknown and too large to store, reading each comment once.

TikTok
Coding & Algorithms
Software Engineer
TikTok
November 29, 2026
Software Engineer
Technical Screen
Coding & Algorithms
Medium

0

0

0 solved


For quality review, sample exactly k comments uniformly at random from a comment stream whose length is unknown and too large to store, reading each comment once.

TikTok trust and safety teams audit random comment samples to measure moderation precision, and this question tests reservoir sampling in an iterator setting. The interviewer expects Algorithm R, a short proof that every item ends up with probability k/n, and an empirical check.

What the Interviewer Expects
  • Rules out storing the stream or knowing its length
  • Fills the reservoir with the first k items, then replaces with probability k/(i+1)
  • Uses an inclusive random range correctly
  • Proves uniformity by induction
  • Validates the distribution with a seeded simulation
Key Topics to Cover
reservoir sampling
streams
randomized algorithms
probability proofs
How to Approach This
  1. Clarify input constraints and edge cases before writing code.
  2. Walk through your approach verbally and confirm with the interviewer before coding.
  3. Start with a brute force solution, then optimize. Mention time and space complexity.
  4. Test your solution with examples, including edge cases like empty input or duplicates.
  5. Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
  • How would you sample in parallel across 100 Kafka partitions and merge?
  • How would you do weighted sampling where reported comments are twice as likely?
  • What changes if you need a sample over only the last hour (a sliding window)?
  • How would you make the sample reproducible for an audit?
Sharpen Your Skills on Codemia

Practice similar problems with our interactive workspace, get AI feedback, and track your progress.

Practice DSA Problems
Sample Answer
Requirements

Single pass, O(k) memory, unknown n. When the stream ends, every subset of k items should be equally likely, so each item is in the sample with probability k/n. If n < k, return all items....

High-Level Design

Keep the first k items. For the item at 0-based index i >= k, draw j uniformly from 0..i inclusive; if j < k, replace reservoir[j] with it. So item i enters with probability k/(i+1).

Proof by induc...


Submit Your Answer
Markdown supported

Related Questions