Count Feed Windows Showing Exactly K Distinct Advertisers
Last updated: November 29, 2026
Quick Overview
Given the sequence of advertiser IDs for ads shown in a user's feed and an integer k, count the contiguous windows that contain exactly k distinct advertisers.
Meta
November 29, 20260
0
0 solved
Given the sequence of advertiser IDs for ads shown in a user's feed and an integer k, count the contiguous windows that contain exactly k distinct advertisers.
A Meta Hard that tests whether you know the at-most-k decomposition. Exactly k is not monotone in the window, so a single sliding window fails, and the interviewer wants to see you notice that and fix it cleanly.
What the Interviewer Expects
- Explains why a single window cannot count exactly-k windows directly
- Expresses exactly(k) as atMost(k) minus atMost(k - 1)
- Implements atMost(k) with a count map, adding window length per right edge
- Gives O(n) time overall
- Tests k = 1 and a k larger than the distinct total
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
- Do it in one pass with two left pointers instead of two calls.
- Count windows with at least k distinct advertisers.
- Count windows where every advertiser appears at most twice.
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: ads, a list of advertiser IDs, and k >= 1. Output: the number of subarrays with exactly k distinct IDs. Length up to 2 * 10^4....
High-Level Design
Counting windows with at most k distinct values is easy: for each right edge, shrink until the map has at most k keys, and then every window ending here and starting in [left, right] qualifies, cont...