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
INPUTALGORITHMRESULT12134Array: [1,2,1,3,4,2,3]Window Size K = 4TaskCount distinct elementsin each window of size 41Build frequency map2Count distinct in first window3Slide window right4Update map and countFrequency TrackingWindow: [2,1,3,4]Map: {1:1, 2:1, 3:1, 4:1}Distinct Count: 4Time: O(n) | Space: O(k)3443Output: [3,4,4,3]Window 1Window 2Window 3Window 4Verification[1,2,1,3] → {1,2,3} = 3[2,1,3,4] → {1,2,3,4} = 4Sliding window works!Key Insight:Instead of recounting distinct elements for each window, maintain a frequency mapand update counts as elements slide in and out of the window - O(n) vs O(n×k)!TutorialsPoint - Count Distinct in Windows | Sliding Window with HashMap
Asked in
Google 42 Amazon 38 Microsoft 29 Meta 24
23.4K Views
Medium-High Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen