January 18, 2025 |3.3K Views

Count Subarrays With At Most K Distinct Elements

Explore Courseexplore course icon
Description
Discussion

To find the count of subarrays with at most k distinct elements, two approaches can be applied. The naive approach involves exploring all possible subarrays using nested loops. For each subarray, a hash set is used to track distinct elements, and if the size of the set is less than or equal to k, the subarray is counted. Although straightforward, this approach has a time complexity of O(n^2), making it inefficient for larger arrays.

The optimal approach uses the Sliding Window Technique with two pointers and a frequency map. As the window expands with the right pointer, the frequency of elements is tracked, and the left pointer shrinks the window when the distinct element count exceeds k. Each window contributes (right−left+1) subarrays to the result. This method efficiently counts subarrays in O(n) time and O(n) space, making it suitable for large datasets.

For more details, please go through - Count Subarrays With At Most K Distinct Elements