Pick an Ad Proportional to Its Bid with Repeated Sampling
Last updated: November 29, 2026
Quick Overview
Given a list of ads and positive integer bid weights, build a sampler whose sample() returns ad i with probability weight[i] / total, optimized for many samples after a one-time setup.
0
0
0 solved
Given a list of ads and positive integer bid weights, build a sampler whose sample() returns ad i with probability weight[i] / total, optimized for many samples after a one-time setup.
Framed around ad auctions and exploration in Google Ads, this checks that you can turn weights into a cumulative distribution and binary search it. Interviewers then shift constraints: weights change often, or you need O(1) sampling, which leads to Fenwick trees or the alias method.
What the Interviewer Expects
- Builds a prefix sum array of weights
- Draws a uniform integer in [1, total] and binary searches the first prefix at least that value
- Gets the off-by-one right so zero-weight ads are never chosen
- States O(n) setup and O(log n) per sample
- Describes the alias method for O(1) sampling
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 update frequently between samples; what structure keeps both operations fast?
- Sample k distinct ads without replacement, proportional to weight.
- Weights are floats and the total is huge; any numerical concerns?
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: items and nonnegative integer weights with positive total.
sample()returns item i with probabilityw[i] / W.- Setup once, sample many times....
High-Level Design
Compute cumulative sums cum[i] = w[0] + ... + w[i]. Draw an integer r uniformly from 1 to W. The answer is the smallest i with cum[i] >= r, found with bisect_left. Item i owns exactly the inte...