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.

Google
Coding & Algorithms
Software Engineer
Google
November 29, 2026
Software Engineer
Phone Screen
Coding & Algorithms
Medium

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
Prefix Sums
Binary Search
Randomization
Probability
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
  • 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 Problems
Sample Answer
Requirements
  • Input: items and nonnegative integer weights with positive total.
  • sample() returns item i with probability w[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...


Submit Your Answer
Markdown supported