Problem 358415 · medium · Level 03 Linear Management & Searching

Distinct Values per Window

sliding window · fixed-size window · hash map

Given a list of integers nums and a window size k, return a list where element i is the number of distinct values in nums[i:i + k], for every valid start i (so the result has len(nums) - k + 1 entries).

Examples

Input:  nums = [5, 5, 7, 5, 9, 7, 7], k = 3
Output: [2, 2, 3, 3, 2]
Explanation: [5,5,7] has 2 distinct, [5,7,5] has 2, [7,5,9] has 3, [5,9,7] has 3, [9,7,7] has 2.

Input:  nums = [8, 8, 8, 3, 4, 3], k = 2
Output: [1, 1, 2, 2, 2]

Constraints

  • 1 <= k <= len(nums) <= 10**5
  • -10**9 <= nums[i] <= 10**9
  • Target complexity: O(n) time; building a set for every window is too slow for the largest tests.

Goals

  • Maintain a frequency map for the current window
  • Update the distinct count only when a frequency crosses zero
Starting Python…