Data Streams
Reservoir Sampling
A clever algorithm for selecting a random sample of `k` items from a data stream of unknown size, ensuring every item has an equal chance of being selected.
Select k Items from a Stream
This implementation of Reservoir Sampling (Algorithm R) creates a reservoir of size `k` and processes the stream, replacing elements with a decreasing probability.
function reservoirSample(stream, k) {
const reservoir = [];
let i = 0;
for (const item of stream) {
if (i < k) {
reservoir.push(item);
} else {
const j = Math.floor(Math.random() * (i + 1));
if (j < k) {
reservoir[j] = item;
}
}
i++;
}
return reservoir;
}
AI Coach Hint: The probability magic happens in the `else` block. For the i-th item (where i >= k), the probability of it being selected is k/i. This ensures that after processing n items, every item has a k/n probability of being in the reservoir.
Related Algorithm Guides
Explore more algorithm interview guides powered by AI coaching
Interview Salary Negotiation Techniques
AI-powered interview preparation guide
Compensation Discussion Interview Preparation
AI-powered interview preparation guide
Slide Deck Presentation Interview Tips
AI-powered interview preparation guide
Logistics Supply Chain Analyst Interview Questions
AI-powered interview preparation guide
Related Algorithm Resources
All Interview Solutions
Browse our complete collection of AI-powered interview preparation guides.
GeeksforGeeks Algorithms
Comprehensive algorithm tutorials and practice problems.
LeetCode Practice
Algorithm coding challenges and interview preparation.
Algorithm Visualizations
Interactive visualizations for understanding algorithms.