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
Coding & Algorithms
Software Engineer
Meta
November 29, 2026
Software Engineer
Onsite
Coding & Algorithms
Hard

0

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
sliding window
at most k trick
hash map
subarray counting
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
  • 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 Problems
Sample 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...


Submit Your Answer
Markdown supported