Count distinct values in every sliding window
I was asked this
No reports yet. Sign in to say where you were asked it.
A coding interview question asked at Google, Microsoft and Meta. It tests sliding window, hash map and arrays.
Given an integer array nums and a window size k, return a list with one entry per contiguous window of length k (there are len(nums) - k + 1 of them). Each entry is the number of different values inside that window.
Implement:
def count_distinct_in_windows(nums: list[int], k: int) -> list[int]: ...
Constraints
1 <= k <= len(nums) <= 10^5- Values can be any integers: negative, zero, or positive.
- Aim for better than O(n * k) time.
Example 1
nums = [4, 4, 7, 2, 7, 4, 9], k = 3
output: [2, 3, 2, 3, 3]
The windows are [4,4,7], [4,7,2], [7,2,7], [2,7,4], [7,4,9].
Example 2
nums = [-1, 0, -1, 0, 1], k = 2
output: [2, 2, 2, 2]
Clarifying questions
- Is
kalways at mostlen(nums)? - Are the values small enough to use an array of counts, or should I use a hash map?
- Should the result have exactly
len(nums) - k + 1entries?
What a strong answer covers
- A sliding window with a hash map of counts: add the new value on the right, remove the value leaving on the left, and delete a key when its count reaches zero. The number of keys is the answer for that window.
- O(n) time and O(k) space.
- Edge cases:
k = 1(all ones),k = len(nums)(one window), all values equal, negative values and zero. - Tests: both examples, the edge cases, and a comparison with
len(set(window))for every window on random inputs.
Follow-ups
- Answer distinct counts for arbitrary ranges
[l, r]given as queries (offline with a Fenwick tree, or Mo's algorithm). - Find the longest window with at most
ddistinct values. - The values arrive as a stream.
Where it's asked
What it tests
Sign in to see the worked answer
The full answer, chapter by chapter, with what interviewers expect at each level. New accounts get 5 credits: each one unlocks a question for good.
What the labs asked this week
A weekly email of what OpenAI, Anthropic and the other top AI labs asked engineers, round by round.
Sign in to submit your code; every attempt is kept here.


