Java | using sliding window and hashmap
\n public int subarraysWithKDistinct(int[] A, int K) {\n        int n = A.length;\n        int c = 0;\n        \n        HashMap<Integer, Integer> m = new HashM
```\n public int subarraysWithKDistinct(int[] A, int K) {\n        int n = A.length;\n        int c = 0;\n        \n        HashMap<Integer, Integer> m = new HashMap<>();\n        int i=0,j=0; // i is starting pointer and j is end pointer\n        while(j<n && i<n){\n            m.put(A[j], m.getOrDefault(A[j], 0)+1);\n            \n            while(m.size()>K){\n                m.put(A[i], m.get(A[i])-1);\n                if(m.get(A[i])<=0){\n                    m.remove(A[i]);\n                }\n                i++;\n            }\n            int prev = i;\n            while(i<=j && m.size()==K) { //i==j incase of K=1\n                m.put(A[i], m.get(A[i])-1);\n                if(m.get(A[i])<=0){\n                    m.remove(A[i]);\n                }\n                i++;\n                c++;\n            } \n            \n            while(prev!=i){\n                i--;\n                m.put(A[i], m.getOrDefault(A[i], 0)+1); \n                // now get back to the state you previously were\n            }\n            j++;   \n            \n        }\n        return c;\n    }\n```
['Sliding Window', 'Java']