Randomly Fill Ad Slots Under Per-User View Caps
Arrays & HashingModel answerLast updated
Randomly assign eligible ads to page positions for one user, respecting per-user display caps, avoiding repeats when possible, and returning the updated view counts.
Ad slot filling for a single user
A page has several named slots (for example "top", "sidebar", "bottom"). You need to decide which ad appears in each slot for one particular user, while respecting how often that user may see each ad.
Inputs
positions: a list of slot names.candidateAds: a list of objects{ adId: string, perUserLimit: number }.adIdis unique, andperUserLimitis the most times this ad may ever be shown to this user.userAdState: a map fromadIdto the number of times that ad has already been shown to this user. An ad missing from the map has been shown 0 times.
Task
Write a function that returns a pair: (assignments, updatedUserAdState). assignments maps every position to an adId, or to null if it could not be filled.
Rules
- Choose among eligible ads at random.
- An ad is eligible only if its current count is strictly less than its
perUserLimit. - If the number of eligible ads is at least the number of positions, every position must get a different ad within this call.
- If there are fewer eligible ads than positions, fill as many positions as you can. An ad may appear in more than one position in this case, but only while its remaining allowance (limit minus count, including views granted earlier in this same call) stays above zero.
- Each placement increases that ad's count in the state by one.
- Return both the assignment and the updated state.
Example
positions = ["top", "middle", "bottom"]
candidateAds = [
{ adId: "ad_a", perUserLimit: 2 },
{ adId: "ad_b", perUserLimit: 1 },
{ adId: "ad_c", perUserLimit: 3 }
]
userAdState = { "ad_a": 1, "ad_b": 1 }
ad_b is exhausted. ad_a has 1 view left and ad_c has 3. One valid result is:
assignments = { top: "ad_c", middle: "ad_a", bottom: "ad_c" }
updatedUserAdState = { ad_a: 2, ad_b: 1, ad_c: 2 }
Because selection is random, other valid outputs exist (for example, ad_a and ad_c swapping places). Note that a stricter reading of rule 4 ("never repeat an ad within one call") would leave bottom as null. Say which interpretation you are implementing and why; this write-up follows the rules as written, where filling more positions wins.
Expected from you
- A working implementation, with a short justification of correctness.
- Time and space complexity.
- Handling of edge cases (empty inputs, bad limits, duplicate ids).
- A brief discussion of how you would make it testable and how it would behave under concurrent requests for the same user.
Hints
Hint 1
Convert each eligible ad into a remaining allowance (limit minus current count) and drop anything at zero. Everything after that can be driven by these allowances rather than by re-checking the original counts.
Hint 2
Split the work in two passes: first give out distinct ads by shuffling the eligible list and pairing it with the positions; only if positions are still empty, move on to a second pass that is allowed to repeat ads.
Hint 3
In the repeat pass, keep a pool of ads that still have allowance, pick a random one, decrement its allowance, and remove it from the pool in O(1) by swapping it with the last element and popping when it reaches zero.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Clarify first
Before coding, I would confirm a few points:
- Eligibility:
(state[adId] ?? 0) < perUserLimit. The remaining allowance isperUserLimit - count. - Mutation: I would return a new state object rather than mutating the input. The caller then never sees a half-updated state if something fails.
- Unfilled slots: map to
null. - Example vs. rule 4: the written rules say to fill as many slots as possible, reusing an ad when its allowance permits. A stricter "no repeats in one call" reading would leave a slot empty in the example. I would ask which is intended, and implement the written rules by default. Dropping the second phase below gives the strict version.
Approach
Model each eligible ad by its remaining allowance and fill the slots in two phases.
- Distinct phase. Shuffle the eligible ads (Fisher-Yates) and pair them with the positions in order, up to
min(#positions, #eligible). Shuffling then pairing gives a uniformly random injective assignment. If there are at least as many eligible ads as positions, every slot is filled with a different ad and we are done, which satisfies rule 3. - Reuse phase. This only runs when eligible ads are fewer than positions. Build a pool of ads whose allowance is still above zero. For each unfilled slot, pick a random pool member, assign it, decrement its allowance, and remove it from the pool once the allowance hits zero. If the pool empties, the remaining slots stay
null.
Every placement increments the ad's count in the copied state.
Why it is correct
- Limits hold. An ad is in the pool only with allowance greater than zero, and each placement consumes one unit. Total placements for an ad therefore never exceed
limit - initialCount, even across reuse within a single call. - Distinctness when possible. If eligible ads cover all positions, phase 1 fills everything and phase 2 never runs.
- Maximum fill. The best possible number of filled slots is
min(#positions, total remaining allowance). We leave a slot empty only when the pool is empty, meaning all allowance is spent, so we hit that bound. - Randomness. Phase 1 is a uniform random selection of distinct ads. Phase 2 picks uniformly among ads that still have allowance. (If you need an exactly uniform distribution over all valid outcomes, you would have to define that distribution first; for ad rotation, this is the usual and acceptable choice.)
Complexity
With P positions and A candidate ads:
- Time: O(A + P). Building allowances is O(A), the shuffle is O(A), and each reuse pick is O(1) thanks to swap-and-pop. Using
Array.prototype.spliceorindexOffor removal would degrade phase 2 to O(P * A). - Space: O(A + P) for the allowance map, pool, state copy, and result.
TypeScript implementation
interface Ad { adId: string; perUserLimit: number }
function assignAds(
positions: string[],
candidateAds: Ad[],
userAdState: Record<string, number>,
rand: () => number = Math.random,
): [Record<string, string | null>, Record<string, number>] {
const state: Record<string, number> = { ...userAdState };
// Remaining allowance per eligible ad; first occurrence of an id wins.
const remaining = new Map<string, number>();
const seen = new Set<string>();
for (const ad of candidateAds) {
if (seen.has(ad.adId)) continue;
seen.add(ad.adId);
const left = ad.perUserLimit - (state[ad.adId] ?? 0);
if (left > 0) remaining.set(ad.adId, left);
}
const slots = [...new Set(positions)]; // dedupe, keep order
const result: Record<string, string | null> = {};
for (const p of slots) result[p] = null;
const place = (pos: string, id: string) => {
result[pos] = id;
state[id] = (state[id] ?? 0) + 1;
remaining.set(id, remaining.get(id)! - 1);
};
// Phase 1: distinct ads
const eligible = [...remaining.keys()];
for (let i = eligible.length - 1; i > 0; i--) {
const j = Math.floor(rand() * (i + 1));
[eligible[i], eligible[j]] = [eligible[j], eligible[i]];
}
const k = Math.min(slots.length, eligible.length);
for (let i = 0; i < k; i++) place(slots[i], eligible[i]);
// Phase 2: reuse ads that still have allowance
const pool = eligible.filter((id) => remaining.get(id)! > 0);
for (let i = k; i < slots.length && pool.length > 0; i++) {
const idx = Math.floor(rand() * pool.length);
const id = pool[idx];
place(slots[i], id);
if (remaining.get(id) === 0) {
pool[idx] = pool[pool.length - 1];
pool.pop();
}
}
return [result, state];
}
On the example, ad_b is dropped, phase 1 pairs ad_a and ad_c with two slots in random order, and phase 2 gives the last slot to ad_c (the only ad left in the pool), producing counts {ad_a: 2, ad_b: 1, ad_c: 2}.
Edge cases
- Empty
positions: return{}and an unchanged copy of the state. - No eligible ads: all slots are
null. - Ads absent from the state count as 0 views.
perUserLimit <= 0or count at or above the limit: ineligible.- Duplicate
adIds in the candidates: keep the first so allowance is not double counted. - Duplicate position names would collide as object keys; dedupe them or clarify that they cannot occur.
- State entries for non-candidate ads must be preserved untouched.
Common mistakes
- Re-checking the original count instead of tracking allowance, which lets an ad exceed its limit when reused within one call.
- Picking randomly with replacement in phase 1, producing duplicates when enough distinct ads exist.
- Mutating the caller's state and then failing midway.
- Removing from the pool with
splice, or filtering the pool for each slot, which turns a linear algorithm quadratic. - Hard-coding
Math.random, which makes tests flaky. Inject the random source so tests can be deterministic.
Follow-ups worth preparing
- Concurrency: two simultaneous requests for the same user can both read the same counts and overshoot a limit. Use atomic conditional increments (for example a Redis script that checks and increments, or compare-and-set in a database) and retry or fall back to another ad when the increment is rejected.
- Weighted choice: replace uniform picks with weighted sampling (by bid or predicted click rate), for example via a prefix-sum or alias table, while keeping the limit logic unchanged.
- Additional caps: global campaign budgets or per-day frequency limits become extra eligibility conditions evaluated alongside the per-user check.