To find the count of subarrays with exactly k distinct elements, two approaches can be utilized. The naive approach involves iterating over all possible subarrays while using a hash set to track distinct elements. For each subarray, the result is incremented if the size of the hash set equals k. Though simple, this approach has a time complexity of O(n^2), which becomes impractical for large arrays.
The optimized approach leverages the sliding window technique and the formula: K=atMostK−atMost(k−1). By calculating subarrays with at most k and k−1 distinct elements, their difference gives the count of subarrays with exactly k distinct elements. This method efficiently processes the array in O(n) time and O(n) space using frequency maps, making it more suitable for large datasets.
For more details, please go through - Count Subarrays With Exactly K Distinct Elements