Distinct Values in Every Window

EasySliding Window≈ 20 min

You are given a list of integers nums and a window size k. A window is k numbers in a row. For every window, from the one that starts at index 0 to the one that ends at the last number, count how many different values it holds. Return the counts, in order.

There are len(nums) − k + 1 windows, so the answer holds that many counts.

Examples

text
nums = [1, 2, 1, 3, 4, 2, 3], k = 4   →  [3, 4, 4, 3]
nums = [5, 5, 5, 5], k = 2            →  [1, 1, 1]
nums = [1, 2, 3], k = 1               →  [1, 1, 1]
nums = [1, 2, 3], k = 3               →  [3]

In the first example the windows are [1, 2, 1, 3] (3 different values), [2, 1, 3, 4] (4), [1, 3, 4, 2] (4) and [3, 4, 2, 3] (3).

Constraints

  • Between 1 and 20,000 numbers, each between -1,000,000,000 and 1,000,000,000.
  • k is at least 1 and at most the length of the list.
  • Aim for O(n): building each window's values from scratch costs n × k.
Sound off. Turn on for key clicks and a chime when the tests pass.Inline suggestions off. Recommended while you are learning. Turn on to complete words as you type.
Console
›Run to see what your code prints

Run checks the 4 visible cases here, in your browser. Submit runs all 8 on the judge, 4 of them hidden, and measures how your solution scales.