Java Solution using Two pointers and HashMap
\t class Solution {\n\t\tpublic int subarraysWithKDistinct(int[] nums, int K) {\n\t\t\tMap map = new HashMap<>();\n\n\t\t\tint first=0;\n\t\t\tint second = 0;\n
\t class Solution {\n\t\tpublic int subarraysWithKDistinct(int[] nums, int K) {\n\t\t\tMap<Integer,Integer> map = new HashMap<>();\n\n\t\t\tint first=0;\n\t\t\tint second = 0;\n\t\t\tint count = 0;\n\n\t\t\twhile(second < nums.length){\n\t\t\t\tmap.put(nums[second],map.getOrDefault(nums[second],0)+1);           \n\t\t\t\tif(map.size()>K){\n\t\t\t\t\tmap.clear();\n\t\t\t\t\tfirst++;\n\t\t\t\t\tsecond = first;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tif(map.size() == K){\n\t\t\t\t\tcount++;\n\t\t\t\t\tsecond++;\n\t\t\t\t\tif(second == nums.length){\n\t\t\t\t\t\tmap.clear();\n\t\t\t\t\t\tfirst++;\n\t\t\t\t\t\tsecond = first;\n\t\t\t\t\t}\n\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tsecond++;\n\n\t\t\t}\n\n\t\t\treturn count;\n        \n\t\t}\n\t}\n\t\n\t\n\t\n\tThe Idea is to iterate the second pointer until the size of the map is equal to k and then clear the map and move the first pointer.
[]