criskgl
12/2/2019 - 5:53 PM

Subarrays with K distinct characters

public static int subarraysWithKDistinct(int[] arr, int k) {
    if(k==0) return 0;
    int n = arr.length;
    Map < Integer, Integer > map = new HashMap < > ();
    int i = 0, j = 0, total = 0;
    while (j < arr.length) {
        map.put(arr[j], map.getOrDefault(arr[j], 0) + 1);
        if (map.size() == k) {
            int dups = j;//at this point we already have K distinct
            while ((dups + 1) < n && map.containsKey(arr[dups + 1])) dups++;//extend our windows as much as we can
            while (map.size() == k) {
                total += (dups - j) + 1;//sum to the total the number of extension + the first array with K distinct
                int removable = arr[i];
                map.put(removable, map.get(removable) - 1);//take out from original K distinct array
                if (map.get(removable) == 0) map.remove(removable);
                i++;
            }
        }
        j++;
    }
    return total;
}