Count Ad Slot Sequences Served by Exactly K Distinct Advertisers
Last updated: November 29, 2026
Quick Overview
Given the advertiser ID shown in each consecutive ad slot and an integer k, count the contiguous slot ranges that contain exactly k distinct advertisers.
0
0
0 solved
Given the advertiser ID shown in each consecutive ad slot and an integer k, count the contiguous slot ranges that contain exactly k distinct advertisers.
A Google onsite Hard problem framed around diversity rules in ad serving. The trick interviewers want is that exactly-k windows are not monotone, but at-most-k windows are, so the answer is atMost(k) minus atMost(k - 1).
What the Interviewer Expects
- Explains why a single exactly-k window does not work
- Uses atMost(k) minus atMost(k - 1)
- Counts `right - left + 1` subarrays per right edge in atMost
- Deletes zero-count keys from the frequency map
- States O(n) time
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
- Can you do it in one pass with two left pointers?
- Count ranges with between a and b distinct advertisers.
- How would you handle a stream and report counts for the last N slots?
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: list
adsof advertiser IDs, integerk >= 1. - Output: number of index pairs
(i, j)withi <= jsuch thatads[i..j]has exactlykdistinct values....
High-Level Design
For a fixed right edge, the set of valid left edges for exactly k distinct is a range in the middle, not a prefix or suffix, so a single shrinking window cannot count it. But windows with at most k di...