Count Distinct in Windows - Problem
Given an array of integers and a window size K, count the number of distinct elements in every contiguous window of size K.
For example, if the array is [1, 2, 1, 3, 4, 2, 3] and K = 4, then the windows are:
- Window 1:
[1, 2, 1, 3]→ 3 distinct elements - Window 2:
[2, 1, 3, 4]→ 4 distinct elements - Window 3:
[1, 3, 4, 2]→ 4 distinct elements - Window 4:
[3, 4, 2, 3]→ 3 distinct elements
Return an array containing the count of distinct elements for each window.
Input & Output
Example 1 — Basic Case
$
Input:
nums = [1,2,1,3,4,2,3], k = 4
›
Output:
[3,4,4,3]
💡 Note:
Window [1,2,1,3] has distinct elements {1,2,3} = 3 count. Window [2,1,3,4] has {1,2,3,4} = 4 count. Window [1,3,4,2] has {1,2,3,4} = 4 count. Window [3,4,2,3] has {2,3,4} = 3 count.
Example 2 — All Same Elements
$
Input:
nums = [1,1,1,1,1], k = 3
›
Output:
[1,1,1]
💡 Note:
Every window of size 3 contains only the element 1, so distinct count is always 1.
Example 3 — All Different Elements
$
Input:
nums = [1,2,3,4], k = 2
›
Output:
[2,2,2]
💡 Note:
Window [1,2] has 2 distinct, [2,3] has 2 distinct, [3,4] has 2 distinct elements.
Constraints
- 1 ≤ nums.length ≤ 105
- 1 ≤ k ≤ nums.length
- -106 ≤ nums[i] ≤ 106
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code