Java Solution with explanation
\n//This is really good question.\n//here the logic is to get all subarrays of size K then get all subarrays of size k-1 the return the ans as no of Subarrays(k
```\n//This is really good question.\n//here the logic is to get all subarrays of size K then get all subarrays of size k-1 the return the ans as no of Subarrays(k)-no of subarrays(k-1) this is the number of arrays with exact k distinct elements.\n\n\nclass Solution {\n     public int subarraysWithKDistinct(int[] nums, int k) {\n         \n         \n      return subarraysWithKSize(nums,k)-subarraysWithKSize(nums,k-1);   \n     }\n      public int subarraysWithKSize(int[] nums, int k) {\n\t       HashMap<Integer,Integer> hs=new HashMap<>();\n\t     int count=0;\n\t        int i=0;\n\t        int j=0;\n\t        while(j<nums.length){\n                  hs.put(nums[j],hs.getOrDefault(nums[j],0)+1);\n              \n\t            \n\t           \n\t           while(hs.size()==k+1){ //while(hs.size()>k){ this is taking more time\n\t              hs.put(nums[i],hs.get(nums[i])-1);\n\t                  if(hs.get(nums[i])==0)\n\t                     hs.remove(nums[i]);\n\t                i++;\n\t                \n\t            }\n                \n                count+=j-i+1;\n                j++;\n\n\t        }\n\t        \n\t        \n\t        return count;\n\t        \n\t    }\n}\n```
['Sliding Window', 'Java']