Java solution using sliding window and map
\nclass Solution {\n    \n    public int subarraysWithKDistinct(int[] ar, int k) {\n\t    // exact(k) == atMost(k) + atMost(k - 1)\n        return atMostK(ar, k
```\nclass Solution {\n    \n    public int subarraysWithKDistinct(int[] ar, int k) {\n\t    // exact(k) == atMost(k) + atMost(k - 1)\n        return atMostK(ar, k) - atMostK(ar, k-1);\n    }\n    \n    private int atMostK(int[] arr, int k) {\n        Map<Integer, Integer> countMap = new HashMap<>();\n        int left = 0;\n        int count = 0;\n        for (int right = 0; right < arr.length; right++) {\n            int num = arr[right];\n            addToMap(countMap, num);\n            while (countMap.size() > k) {\n                removeFromMap(countMap, arr[left]);\n                left++;\n            }\n            count += right - left + 1;\n        }\n        return count;\n    }\n    \n    private void addToMap(Map<Integer, Integer> countMap, int num) {\n        countMap.put(num, countMap.getOrDefault(num, 0) + 1);\n    }\n\n    private void removeFromMap(Map<Integer, Integer> countMap, int num) {\n        countMap.put(num, countMap.getOrDefault(num, 0) - 1);\n        if (countMap.get(num) <= 0) {\n            countMap.remove(num);\n        }\n    }\n}\n```
['Sliding Window', 'Java']