VOOZH about

URL: https://www.geeksforgeeks.org/dsa/count-distinct-elements-in-every-window-of-size-k/

⇱ Count Distinct In Every Window of Size K - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Count Distinct In Every Window of Size K

Last Updated : 14 Mar, 2026

Given an array arr[] and an integer k, return the count of distinct numbers in all windows of size k. 

Examples:

Input: arr[] = [1, 2, 1, 3, 4, 2, 3], k = 4
Output: [3, 4, 4, 3]
Explanation: First window is [1, 2, 1, 3], count of distinct numbers is 3.
                      Second window is [2, 1, 3, 4] count of distinct numbers is 4.
                      Third window is [1, 3, 4, 2] count of distinct numbers is 4.
                      Fourth window is [3, 4, 2, 3] count of distinct numbers is 3.

Input: arr[] = [4, 1, 1], k = 2
Output: [2, 1]
Explanation: First window is [4, 1], count of distinct numbers is 2.
                      Second window is [1, 1], count of distinct numbers is 1.

[Naive Approach] Traversal and Hashing - O(n × k) Time and O(1) Space

Traverse the given array considering every window of size k in it and keep a count on the distinct elements of the window.


Output
3 4 4 3 

[Expected Approach] Sliding Window and Hashing - O(n) Time and O(k) Space

  • Use a sliding window of size k and store element frequencies in a hash map.
  • Initialize the first window with the first k elements; the map size gives the number of distinct elements.
  • Slide the window, add the new element, remove the old one (if its frequency becomes 0 remove it), and store the map size as the result.

Output
3 4 4 3 
Comment