Given an array of size n and an integer k, return the count of distinct numbers in all windows of size k.
Example:
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[] = {1, 2, 4, 4};
k = 2
Output: 2 2 1
Explanation:
First window is {1, 2}, count of distinct numbers is 2
First window is {2, 4}, count of distinct numbers is 2
First window is {4, 4}, count of distinct numbers is 1
Source: This problem has appeared in Microsoft Interview Question.
Naive Approach: The naive solution is to traverse the given array considering every window in it and keeping a count on the distinct elements of the window.
-
Algorithm:
- For every index i from 0 to len_array(n) – k, i.e n – k, traverse the array from i to i + k. This is the window
- Traverse the window, from i to that index and check if the element is present or not.
- If the element is not present in the prefix of the array, i.e no duplicate element is present from i to index-1, then increase the count.
- Print the count.
-
Implementation:
C++
// Simple C++ program to count distinct// elements in every window of size k#include <bits/stdc++.h>usingnamespacestd;// Counts distinct elements in window of size kintcountWindowDistinct(intwin[],intk){intdist_count = 0;// Traverse the windowfor(inti = 0; i < k; i++) {// Check if element arr[i] exists in arr[0..i-1]intj;for(j = 0; j < i; j++)if(win[i] == win[j])break;if(j == i)dist_count++;}returndist_count;}// Counts distinct elements in all windows of size kvoidcountDistinct(intarr[],intn,intk){// Traverse through every windowfor(inti = 0; i <= n - k; i++)cout << countWindowDistinct(arr + i, k) << endl;}// Driver programintmain(){intarr[] = { 1, 2, 1, 3, 4, 2, 3 }, k = 4;intn =sizeof(arr) /sizeof(arr[0]);countDistinct(arr, n, k);return0;}chevron_rightfilter_noneJava
// Simple Java program to count distinct elements in every// window of size kimportjava.util.Arrays;classTest {// Counts distinct elements in window of size kstaticintcountWindowDistinct(intwin[],intk){intdist_count =0;// Traverse the windowfor(inti =0; i < k; i++) {// Check if element arr[i] exists in arr[0..i-1]intj;for(j =0; j < i; j++)if(win[i] == win[j])break;if(j == i)dist_count++;}returndist_count;}// Counts distinct elements in all windows of size kstaticvoidcountDistinct(intarr[],intn,intk){// Traverse through every windowfor(inti =0; i <= n - k; i++)System.out.println(countWindowDistinct(Arrays.copyOfRange(arr, i, arr.length), k));}// Driver methodpublicstaticvoidmain(String args[]){intarr[] = {1,2,1,3,4,2,3}, k =4;countDistinct(arr, arr.length, k);}}chevron_rightfilter_nonePython3
# Simple Python3 program to count distinct# elements in every window of size kimportmath as mt# Counts distinct elements in window# of size kdefcountWindowDistinct(win, k):dist_count=0# Traverse the windowforiinrange(k):# Check if element arr[i] exists# in arr[0..i-1]j=0whilej < i:if(win[i]==win[j]):breakelse:j+=1if(j==i):dist_count+=1returndist_count# Counts distinct elements in all# windows of size kdefcountDistinct(arr, n, k):# Traverse through every windowforiinrange(n-k+1):print(countWindowDistinct(arr[i:k+i], k))# Driver Codearr=[1,2,1,3,4,2,3]k=4n=len(arr)countDistinct(arr, n, k)# This code is contributed by# Mohit kumar 29chevron_rightfilter_noneC#
// Simple C# program to count distinct// elements in every window of size kusingSystem;usingSystem.Collections.Generic;classGFG {// Counts distinct elements in// window of size kstaticintcountWindowDistinct(int[] win,intk){intdist_count = 0;// Traverse the windowfor(inti = 0; i < k; i++) {// Check if element arr[i]// exists in arr[0..i-1]intj;for(j = 0; j < i; j++)if(win[i] == win[j])break;if(j == i)dist_count++;}returndist_count;}// Counts distinct elements in// all windows of size kstaticvoidcountDistinct(int[] arr,intn,intk){// Traverse through every windowfor(inti = 0; i <= n - k; i++) {int[] newArr =newint[k];Array.Copy(arr, i, newArr, 0, k);Console.WriteLine(countWindowDistinct(newArr, k));}}// Driver CodepublicstaticvoidMain(String[] args){int[] arr = { 1, 2, 1, 3, 4, 2, 3 };intk = 4;countDistinct(arr, arr.Length, k);}}// This code is contributed by Princi Singhchevron_rightfilter_none -
Output:
3 4 4 3
-
Complexity Analysis:
- Time complexity: O(nk2).
The time complexity can be improved to O(n*k*log k) by modifying countWindowDistinct() by the use of sorting. The function can further be optimized to use hashing to find distinct elements in a window. With hashing the time complexity becomes O(n*k). - Space Complexity: O(1) we no any extra space is needed.
- Time complexity: O(nk2).
Efficient Approach: So, there is an efficient solution using hashing, though hashing requires extra O(n) space but the time complexity will improve. The trick is to use the count of the previous window while sliding the window. To do this a hash map can be used that stores elements of the current window. The hash-map is also operated on by simultaneous addition and removal of an element while keeping track of distinct elements. The problem deals with finding the count of distinct elements in a window of length k, at any step while shifting the window and discarding all the computation done in the previous step, even though k – 1 elements are same from the previous adjacent window. For example, assume that elements from index i to i + k – 1 are stored in a Hash Map as an element-frequency pair. So, while updating the Hash Map in range i + 1 to i + k, reduce the frequency of the i-th element by 1 and increase the frequency of (i + k)-th element by 1.
Insertion and deletion from the HashMap takes constant time.
-
Algorithm:
- Create an empty hash map. Let the hash map be hM.
- Initialize the count of distinct element as dist_count to 0.
- Traverse through the first window and insert elements of the first window to hM. The elements are used as key and their counts as the value in hM. Also, keep updating dist_count
- Print distinct count for the first window.
- Traverse through the remaining array (or other windows).
- Remove the first element of the previous window.
- If the removed element appeared only once, remove it from hM and decrease the distinct count, i.e. do “dist_count–“
- else (appeared multiple times in hM), then decrement its count in hM
- Add the current element (last element of the new window)
- If the added element is not present in hM, add it to hM and increase the distinct count, i.e. do “dist_count++”
- Else (the added element appeared multiple times), increment its count in hM
-
Below is a dry run of the above approach:

- Implementation:
C++
// An efficient C++ program to// count distinct elements in// every window of size k#include <iostream>#include <map>usingnamespacestd;voidcountDistinct(intarr[],intk,intn){// Creates an empty hashmap hmmap<int,int> hm;// initialize distinct element count for current windowintdist_count = 0;// Traverse the first window and store count// of every element in hash mapfor(inti = 0; i < k; i++) {if(hm[arr[i]] == 0) {dist_count++;}hm[arr[i]] += 1;}// Print count of first windowcout << dist_count << endl;// Traverse through the remaining arrayfor(inti = k; i < n; i++) {// Remove first element of previous window// If there was only one occurrence, then reduce distinct count.if(hm[arr[i - k]] == 1) {dist_count--;}// reduce count of the removed elementhm[arr[i - k]] -= 1;// Add new element of current window// If this element appears first time,// increment distinct element countif(hm[arr[i]] == 0) {dist_count++;}hm[arr[i]] += 1;// Print count of current windowcout << dist_count << endl;}}intmain(){intarr[] = { 1, 2, 1, 3, 4, 2, 3 };intsize =sizeof(arr) /sizeof(arr[0]);intk = 4;countDistinct(arr, k, size);return0;}// This solution is contributed by Aditya Goelchevron_rightfilter_noneJava
// An efficient Java program to count distinct elements in// every window of size kimportjava.util.HashMap;classCountDistinctWindow {staticvoidcountDistinct(intarr[],intk){// Creates an empty hashMap hMHashMap<Integer, Integer> hM =newHashMap<Integer, Integer>();// Traverse the first window and store count// of every element in hash mapfor(inti =0; i < k; i++)hM.put(arr[i], hM.getOrDefault(arr[i],0) +1);// Print count of first windowSystem.out.println(hM.size());// Traverse through the remaining arrayfor(inti = k; i < arr.length; i++) {// Remove first element of previous window// If there was only one occurrenceif(hM.get(arr[i - k]) ==1) {hM.remove(arr[i - k]);}else// reduce count of the removed elementhM.put(arr[i - k], hM.get(arr[i - k]) -1);// Add new element of current window// If this element appears first time,// set its count as 1,hM.put(arr[i], hM.getOrDefault(arr[i],0) +1);// Print count of current windowSystem.out.println(hM.size());}}// Driver methodpublicstaticvoidmain(String arg[]){intarr[] = {1,2,1,3,4,2,3};intk =4;countDistinct(arr, k);}}chevron_rightfilter_nonePython3
# An efficient Python program to# count distinct elements in# every window of size kfromcollectionsimportdefaultdictdefcountDistinct(arr, k, n):# Creates an empty hashmap hmmp=defaultdict(lambda:0)# initialize distinct element# count for current windowdist_count=0# Traverse the first window and store count# of every element in hash mapforiinrange(k):ifmp[arr[i]]==0:dist_count+=1mp[arr[i]]+=1# Print count of first windowprint(dist_count)# Traverse through the remaining arrayforiinrange(k, n):# Remove first element of previous window# If there was only one occurrence,# then reduce distinct count.ifmp[arr[i-k]]==1:dist_count-=1mp[arr[i-k]]-=1# Add new element of current window# If this element appears first time,# increment distinct element countifmp[arr[i]]==0:dist_count+=1mp[arr[i]]+=1# Print count of current windowprint(dist_count)arr=[1,2,1,3,4,2,3]n=len(arr)k=4countDistinct(arr, k, n)# This code is contributed by Shrikant13chevron_rightfilter_noneC#
// An efficient C# program to count// distinct elements in every window of size kusingSystem;usingSystem.Collections.Generic;publicclassCountDistinctWindow {staticvoidcountDistinct(int[] arr,intk){// Creates an empty hashMap hMDictionary<int,int> hM =newDictionary<int,int>();// initialize distinct element count for// current windowintdist_count = 0;// Traverse the first window and store count// of every element in hash mapfor(inti = 0; i < k; i++) {if(!hM.ContainsKey(arr[i])) {hM.Add(arr[i], 1);dist_count++;}else{intcount = hM[arr[i]];hM.Remove(arr[i]);hM.Add(arr[i], count + 1);}}// Print count of first windowConsole.WriteLine(dist_count);// Traverse through the remaining arrayfor(inti = k; i < arr.Length; i++) {// Remove first element of previous window// If there was only one occurrence, then// reduce distinct count.if(hM[arr[i - k]] == 1) {hM.Remove(arr[i - k]);dist_count--;}else// reduce count of the removed element{intcount = hM[arr[i - k]];hM.Remove(arr[i - k]);hM.Add(arr[i - k], count - 1);}// Add new element of current window// If this element appears first time,// increment distinct element countif(!hM.ContainsKey(arr[i])) {hM.Add(arr[i], 1);dist_count++;}else// Increment distinct element count{intcount = hM[arr[i]];hM.Remove(arr[i]);hM.Add(arr[i], count + 1);}// Print count of current windowConsole.WriteLine(dist_count);}}// Driver methodpublicstaticvoidMain(String[] arg){int[] arr = { 1, 2, 1, 3, 4, 2, 3 };intk = 4;countDistinct(arr, k);}}// This code contributed by Rajput-Jichevron_rightfilter_none - Output:
3 4 4 3
-
Complexity Analysis:
- Time complexity O(n). As single traversal of the array is required.
- Space Compelxity O(n). Since, the hashmap requires linear space.
This article is contributed by Piyush. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
Recommended Posts:
- Find maximum of minimum for every window size in a given array
- First negative integer in every window of size k
- Maximum possible sum of a window in an array such that elements of same window in other array are unique
- Count all distinct pairs of repeating elements from the array for every array element
- Construct a distinct elements array with given size, sum and element upper bound
- Sliding Window Maximum (Maximum of all subarrays of size k) using stack in O(n) time
- Sliding Window Maximum (Maximum of all subarrays of size k)
- Check if an Array is made up of Subarrays of continuous repetitions of every distinct element
- Split array into maximum subarrays such that every distinct element lies in a single subarray
- Maximum Unique Element in every subarray of size K
- Check if a key is present in every segment of size k in an array
- Print the sequence of size N in which every term is sum of previous K terms
- Count greater elements on the left side of every array element
- Sum of distinct elements when elements are in range 1 to n
- Length of array pair formed where one contains all distinct elements and other all same elements
- Split an array containing N elements into K sets of distinct elements
- Maximum distinct elements after removing k elements
- Count subarrays having total distinct elements same as original array
- Count of subsequences having maximum distinct elements
- Count distinct elements in an array

