Untitled

 avatar
unknown
plain_text
a month ago
1.1 kB
2
Indexable
import java.util.HashMap;

class Solution {
    public int subarraysWithKDistinct(int[] nums, int k) {
        return atMostKDistinct(nums, k) - atMostKDistinct(nums, k - 1);
    }

    private int atMostKDistinct(int[] nums, int k) {
        HashMap<Integer, Integer> map = new HashMap<>(); // To track the frequency of elements in the current window
        int i = 0, count = 0;

        for (int j = 0; j < nums.length; j++) {
            // Add the current element to the map
            map.put(nums[j], map.getOrDefault(nums[j], 0) + 1);

            // If the map size exceeds k, shrink the window
            while (map.size() > k) {
                map.put(nums[i], map.get(nums[i]) - 1);
                if (map.get(nums[i]) == 0) {
                    map.remove(nums[i]); // Remove the element if its count becomes 0
                }
                i++; // Shrink the window from the left
            }

            // Add all valid subarrays ending at j
            count += (j - i + 1);
        }

        return count;
    }
}
Leave a Comment