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.

Google
Coding & Algorithms
Software Engineer
Google
November 29, 2026
Software Engineer
Onsite
Coding & Algorithms
Hard

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
Sliding Window
Counting Subarrays
Inclusion-Exclusion
Hash Map
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
  • 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 Problems
Sample Answer
Requirements
  • Input: list ads of advertiser IDs, integer k >= 1.
  • Output: number of index pairs (i, j) with i <= j such that ads[i..j] has exactly k distinct 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...


Submit Your Answer
Markdown supported