← Questions

Count distinct values in every sliding window

0

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 k always at most len(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 + 1 entries?

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 d distinct values.
  • The values arrive as a stream.

Where it's asked

What it tests

sliding window · hash map · arrays

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding