Enforce a Per-User Impression Frequency Cap in a Sliding Window
Last updated: November 29, 2026
Quick Overview
Implement try_serve(user_id, ts) for an ad server that returns True and records the impression only if the user has seen fewer than N impressions of the campaign in the last W seconds. Timestamps arrive in non-decreasing order.
StackAdapt
November 29, 20260
0
0 solved
Implement try_serve(user_id, ts) for an ad server that returns True and records the impression only if the user has seen fewer than N impressions of the campaign in the last W seconds. Timestamps arrive in non-decreasing order.
Frequency capping is one of the first guardrails every DSP like StackAdapt applies before bidding, because advertisers pay for reach and get annoyed when one person sees the same native ad twenty times. A phone screen uses it to check clean data-structure choice and exact window boundaries.
What the Interviewer Expects
- States the window semantics precisely, impressions in (ts - W, ts]
- Uses a per-user queue and evicts expired timestamps lazily
- Only records an impression when it is actually served
- Gives O(1) amortized time per call and O(N) memory per active user
- Mentions memory cleanup for users who go idle
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
- How would you cap at the campaign level and the advertiser level at the same time?
- The bidder runs on 200 hosts; where does the counter live and what consistency do you need?
- How would you approximate this with fixed buckets to cut memory?
- What changes if timestamps can arrive slightly out of order?
Sharpen Your Skills on Codemia
Practice similar problems with our interactive workspace, get AI feedback, and track your progress.
Practice DSA ProblemsSample Answer
Requirements
Each user may receive at most cap impressions within any trailing window of window seconds. A call that would exceed the cap returns False and must not be recorded, otherwise blocked requests woul...
High-Level Design
Keep a hash map from user id to a deque of the timestamps of served impressions. On each call, pop timestamps that fall at or before ts - window from the front, then compare the remaining length wit...