Sample an Ad Proportional to Its Bid Weight
Last updated: November 29, 2026
Quick Overview
Given positive integer weights for a set of ads, design a class whose pick() returns an ad index with probability equal to its weight divided by the total weight. pick() will be called many times.
Meta
November 29, 20260
0
0 solved
Given positive integer weights for a set of ads, design a class whose pick() returns an ad index with probability equal to its weight divided by the total weight. pick() will be called many times.
Weighted random selection maps directly onto ads auctions and feed experimentation at Meta. Interviewers check for prefix sums plus binary search, careful boundary handling in the search, and awareness of the alias method when picks dominate.
What the Interviewer Expects
- Builds prefix sums once in the constructor
- Uses binary search for O(log n) per pick
- Gets the search boundary right so no index is skewed
- Mentions the alias method for O(1) picks
- Discusses updating weights dynamically
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
- Weights change frequently; how do you support updates in O(log n)?
- Implement Vose's alias method for O(1) picks.
- How would you test that the sampler is unbiased?
Sharpen Your Skills on Codemia
Practice similar problems with our interactive workspace, get AI feedback, and track your progress.
Practice DSA ProblemsSample Answer
Requirements
Weights are non-negative integers with a positive total, up to 10^4 ads. Constructor runs once, pick runs up to 10^5 times. Zero-weight ads must never be picked....
High-Level Design
Build prefix[i] as the sum of weights 0 through i. Draw an integer r uniformly in [1, total]. The answer is the first index where prefix[i] >= r, found with bisect_left. Ad i owns exactly `w...