Problem 358415 · medium · Phase 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 = [1, 2, 3, 2, 2, 1, 3], k = 3
Output: [3, 2, 2, 2, 3]
Explanation: [1,2,3] has 3 distinct, [2,3,2] has 2, [3,2,2] has 2, [2,2,1] has 2, [2,1,3] has 3.

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

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…