Simple Java Solution using Sliding Window | Easy to Understand
Please upvote, if you find it useful :) \n\n\nclass Solution {\n    public int subarraysWithKDistinct(int[] arr, int k) {\n        return solution(arr,k) - solu
Please upvote, if you find it useful :) \n\n```\nclass Solution {\n    public int subarraysWithKDistinct(int[] arr, int k) {\n        return solution(arr,k) - solution(arr, k - 1);\n    }\n    \n    public int solution(int[] arr, int K) {\n        HashMap<Integer, Integer> map = new HashMap<>();\n\t\tint j = 0;\n\t\tint ans = 0;\n\t\tint i = 0;\n\t\tfor(i = 0; i < arr.length; i++) {\n\t\t\tmap.put(arr[i], map.getOrDefault(arr[i], 0) + 1);\n\n\t\t\t\twhile(map.size() > K) {\n\t\t\t\t\tif(map.get(arr[j]) > 1) {\n\t\t\t\t\t\tmap.put(arr[j], map.get(arr[j]) - 1);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tmap.remove(arr[j]);\n\t\t\t\t\t}\n\n\t\t\t\t\tj += 1;\n\t\t\t\t}\n\n\t\t\t\tans += (i-j) + 1;\n\t\t}\n\n\t\treturn ans;\n    }\n}\n```
['Sliding Window', 'Java']