Problem Statement (Asked By Facebook)
You are given a stream of elements that is too large to fit into memory. Write an algorithm to select a random element from the stream with equal probability.
Problem link: N/A
Disclaimer: Try solving the problem on your own first! Use this solution only as a reference to learn and improve.
A naive solution to pick a random element from a stream involves storing all elements in a list, determining the size of the list, and then selecting a random index. However, this approach requires O(N) space, where N is the size of the stream, which is inefficient for very large or infinite streams.
Instead, we can use reservoir sampling, which allows us to select a random element from a stream with O(1) space complexity. The key idea is to maintain a single random element and update it dynamically as we process the stream:
import java.util.Random; public class ReservoirSampling { public static <T> T pickRandomElement(Iterable<T> stream) { Random random = new Random(); T randomElement = null; int index = 0; for (T element : stream) { // Replace the current random element with the current element with probability 1 / (index + 1) if (random.nextInt(index + 1) == 0) { randomElement = element; } index++; } return randomElement; } public static void main(String[] args) { // Example usage Iterable<Integer> stream = java.util.List.of(10, 20, 30, 40, 50); int trials = 100000; int[] counts = new int[5]; // To track frequency of selection for each element for (int i = 0; i < trials; i++) { int picked = pickRandomElement(stream); counts[stream.iterator().next() - 10]++; // Map element to index } // Print frequencies for (int i = 0; i < counts.length; i++) { System.out.printf("Element %d picked %d times\n", 10 + i * 10, counts[i]); } } }
Random
instance is used to generate random numbers.randomElement
stores the currently selected random element.index
keeps track of the current position in the stream.randomElement
with the current element with probability 1/(index+1).randomElement
contains the randomly selected element.This algorithm is ideal for selecting a random element from very large or infinite streams.
Did this solution help you understand the concept better? Let me know your thoughts in the comments below! Don’t forget to follow us on Instagram @coderz.py for more DSA tips and solutions to ace your coding interviews.
The formula for the area of a circle is given by πr². Use the Monte…
Given an integer k and a string s, write a function to determine the length…
There is a staircase with N steps, and you can ascend either 1 step or…
Build an autocomplete system that, given a query string s and a set of possible…
Design a job scheduler that accepts a function f and an integer n. The scheduler…
Problem Statement (Asked By Airbnb) Given a list of integers, write a function to compute…