Count distinct elements in every window | Practice | GeeksforGeeks

Given an array of integers and a number K. Find the count of distinct elements in every window of size K in the array.
Example 1:
Input:
N = 7, K = 4
A[] = {1,2,1,3,4,2,3}
Output: 3 4 4 3
Explanation: Window 1 of size k = 4 is
1 2 1 3. Number of distinct elements in
this window are 3. 
Window 2 of size k = 4 is 2 1 3 4. Number
of distinct elements in this window are 4.
Window 3 of size k = 4 is 1 3 4 2. Number
of distinct elements in this window are 4.
Window 4 of size k = 4 is 3 4 2 3. Number
of distinct elements in this window are 3.

Example 2:
Input:
N = 3, K = 2
A[] = {4,1,1}
Output: 2 1
Your Task:
Your task is to complete the function countDistinct() which takes the array A[], the size of the array(N) and the window size(K) as inputs and returns an array containing the count of distinct elements in every contiguous window of size K in the array A[].
Expected Time Complexity: O(N).
Expected Auxiliary Space: O(N).
Constraints:
1 <= K <= N <= 105
1 <= A[i] <= 105 , for each valid i
0
venkatesh_naidu2 weeks ago
C++ Solution → O(n) Time, O(k) space
class Solution{
  public:
    vector <int> countDistinct (int arr[], int n, int k)
    {
        //code here.
        unordered_map<int, int> f;
        vector<int> res;
        
        // create map for the first window of k items
        for(int i = 0; i < k; i++) {
            if(f.find(arr[i]) == f.end())
                f[arr[i]] = 1;
            else
                f[arr[i]]++;
        }
        
        // distinct numbers count for first window
        int count = f.size();
        res.push_back(count);
        
        for(int i = k; i < n; i++) {
            // decrement count if item is being removed from map
            if(f[arr[i-k]] == 1) {
                f.erase(arr[i-k]);
                count--;
            }
            else {
                f[arr[i-k]]--;
            }

            // increment count if item is being freshly added to map
            if(f.find(arr[i]) == f.end()) {
                f[arr[i]] = 1;
                count++;
            } else {
                f[arr[i]]++;
            }
            
            // append the count for current window
            res.push_back(count);
        }
        
        return res;
    }
};
0
19bcs13142 weeks ago
Using HashMap 
class Solution
{
    ArrayList<Integer> countDistinct(int arr[], int n, int k)
    {
        // code here 
        ArrayList<Integer> ans=new ArrayList<Integer>();
        
        Map<Integer,Integer> map=new HashMap<>();
        
        int j=0,i=0;
        
        while(j<n){
            map.put(arr[j],map.getOrDefault(arr[j],0)+1);
            if(j-i+1<k){
                j++;
            }else if(j-i+1==k){
                ans.add(map.size());
                if(map.get(arr[i])==1){
                    map.remove(arr[i]);
                }
                else if(map.get(arr[i])>1){
                    map.replace(arr[i],map.get(arr[i])-1);
                }
                
                i++;
                j++;
            }
        }
        return ans;
    }
}
 
 
+1
kartikeyashokgautam1 month ago
JAVA Solution :-
 
 ArrayList<Integer> countDistinct(int A[], int n, int k)   {         ArrayList<Integer> al = new ArrayList<>();              HashMap<Integer,Integer> hm = new HashMap<>();               for(int i=0;i<=k-2;i++)       {           hm.put(A[i],hm.getOrDefault(A[i],0)+1);       }              for(int j=0, i=k-1;i<A.length;) // Acquire        {           hm.put(A[i],hm.getOrDefault(A[i],0)+1);                      al.add(hm.size());     // work                      int freq = hm.get(A[j]);           
// Release           if(freq == 1)           {               hm.remove(A[j]);           }                      else           {               hm.put(A[j],freq-1);           }                      i++;           j++;       }   return al;   }
+1
mayank20211 month ago
C++ : 1.5/3.2vector <int> countDistinct (int A[], int n, int k)   {       vector<int> vec;       map<int, int>mp;             // if(k>n) return vec;              for(int i=0; i<k ; i++)        {            mp[A[i]]++;        }        vec.push_back(mp.size());               for(int i=k; i<n ; i++)       {           if(mp[A[i-k]]==1) mp.erase(A[i-k]);           else            mp[A[i-k]]--;           mp[A[i]]++;                        vec.push_back(mp.size());                  }                return vec;   }
0
mummadiug1 month ago
only 200 test cases are passing suggests some changes
from collections import Counterclass Solution:   def countDistinct(self, A, N, K):       m=[]       for i in range(N-K+1):           z=Counter(A[i:i+K])           m.append(len(z))       return m
+1
sagrikasoni
This comment was deleted.
+2
dipeshmakwane1 month ago
Easy C++ Solution :
 vector <int> countDistinct (int A[], int n, int k)
    {
        //code here.
        unordered_map<int,int>um;
        vector<int>v;
        for(int i=0;i<k;i++){
            um[A[i]]++;
        }
        v.push_back(um.size());
        int j=0;
        for(int i=k;i<n;i++){
            um[A[j]]--;
            um[A[i]]++;
            if(um[A[j]]==0){
                um.erase(A[j]);
            }
            j++;
            v.push_back(um.size());
        }
        
        return v;
    }
    
0
avipanwar65651 month ago
vector <int> countDistinct (int A[], int n, int k)   {       vector<int> v;       unordered_map<int, int> m;       for(int i=0; i<k; i++)       {           m[A[i]]++;       }       v.push_back(m.size());       for(int i=k; i<n; i++)       {           if(m[A[i-k]]==1)           {               m.erase(A[i-k]);           }           else           {               m[A[i-k]]--;           }                      m[A[i]]++;           v.push_back(m.size());       }       return v;   }
0
vishwajeetpawar191 month ago
class Solution{
    
  public:
  
    vector <int> countDistinct (int A[], int n, int k)
    {
        //code here.
        map<int,int>mp ;
        vector <int> res ;
        int count = 0 ;
        
        for(int i=0;i<k;i++)
        {
            if(mp.find(A[i])!=mp.end())
            {
                mp[A[i]]++ ;
                continue ;
            }
            mp[A[i]]++ ;
            count++ ;
        }
        res.push_back(count) ;
        
        int left = 0 ;
        
        for(int i=k;i<n;i++)
        {
            mp[A[left]]-- ;
            
            if( mp[A[left]] == 0 )
                count-- ;
                
            mp[A[i]]++ ;
            
            if( mp[A[i]] == 1 )
                count++ ;
                
            res.push_back(count) ;
            left++ ;
        }
        
        return res ;
    }
    
};
+1
dronzerdracel1 month ago
Sliding window concept of Aditya Verma
vector <int> countDistinct (int arr[], int n, int k)
    {
        //code here.
        unordered_map<int,int>mp;
        int i=0,j=0;
        vector<int>v;
        while(j<n){
            mp[arr[j]]++;
            if(j-i+1<k)
              j++;
            else if(j-i+1==k){
                v.push_back(mp.size());
                mp[arr[i]]--;
                if(mp[arr[i]]==0)
                 mp.erase(arr[i]);
                i++;
                j++;
            }  
        }
        return v;
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.