Java || Sliding Window || 4ms || beats 98% || O(A.length)
\n    // O(A.length) O(1)\n\tpublic int subarraysWithKDistinct(int[] A, int K) {\n\t\treturn subarraysWithKAtmost(A, K) - subarraysWithKAtmost(A, K - 1);\n\t}\n
\n    // O(A.length) O(1)\n\tpublic int subarraysWithKDistinct(int[] A, int K) {\n\t\treturn subarraysWithKAtmost(A, K) - subarraysWithKAtmost(A, K - 1);\n\t}\n\n\t// O(A.length) O(1)\n\tpublic int subarraysWithKAtmost(int[] A, int K) {\n\n\t\tint count = 0, ptr1 = 0, ptr2 = 0, len = A.length, ans = 0;\n\t\tint[] freq = new int[20001];\n\n\t\twhile (ptr1 < len) {\n\n\t\t\twhile (ptr1 < len && count <= K) {\n\t\t\t\tint num = A[ptr1];\n\t\t\t\tif (freq[num] == 0)\n\t\t\t\t\tcount++;\n\t\t\t\tfreq[num]++;\n\t\t\t\tptr1++;\n\t\t\t}\n\n\t\t\twhile (count == K + 1) {\n\t\t\t\tans += (ptr1 - ptr2 - 1);\n\t\t\t\tint num = A[ptr2];\n\t\t\t\tfreq[num]--;\n\t\t\t\tptr2++;\n\t\t\t\tif (freq[num] == 0)\n\t\t\t\t\tcount--;\n\t\t\t}\n\n\t\t}\n\n\t\tint n = ptr1 - ptr2;\n\t\tans += (n * (n + 1) / 2);\n\t\treturn ans;\n\t}\n
[]