JAVA Solution with HashMap
\nclass Solution {\n    public int subarraysWithKDistinct(int[] A, int K) {\n        \n    \n        return solve(A, K) - solve(A, K-1);    \n    }\n    \n    p
```\nclass Solution {\n    public int subarraysWithKDistinct(int[] A, int K) {\n        \n    \n        return solve(A, K) - solve(A, K-1);    \n    }\n    \n    public int solve(int[] A, int K){\n        int i=0;\n        int j=0;\n        Map<Integer,Integer> map = new HashMap<>();\n        int ans=0;\n        int n = A.length;\n        while(j<n)\n        {\n            int key = A[j];\n            if(map.containsKey(key))\n            {\n                map.put(key,map.get(key)+1);\n            }\n            else\n            {\n                map.put(key,1);\n            }\n            \n            \n            if(map.size() < K)\n            {\n                ans += j-i+1;\n                j++;\n            }\n            \n            if(map.size()==K)\n            {\n                ans += j-i+1;\n                j++;\n            }\n            \n            if(map.size() > K)\n            {\n               while(map.size() > K)\n               {\n                     map.put(A[i],map.get(A[i])-1);\n                       if(map.get(A[i])==0)\n                       {\n                           map.remove(A[i]);\n                       }\n                      i++;\n                   \n               }\n                ans += j-i+1;\n                j++;\n            }\n            \n        }\n        return ans;\n        \n    }\n}\n```
[]