VOOZH about

URL: https://www.geeksforgeeks.org/dsa/count-of-subarrays-having-exactly-k-distinct-elements/

⇱ Count Subarrays With Exactly K Distinct Elements - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Count Subarrays With Exactly K Distinct Elements

Last Updated : 12 Jul, 2025

Given an array arr[] and an integer k, the task is to find the count of subarrays such that each subarray has exactly k distinct elements.

Examples:

Input: arr[] = [1, 2, 2, 3], k = 2 
Output:
Explanation: Subarrays with exactly 2 distinct elements are: [1, 2], [1, 2, 2] and [2, 3].

Input: arr[] = [3, 1, 2, 2, 3], k = 3 
Output: 4
Explanation: Subarrays with exactly 3 distinct elements are: [3, 1, 2], [3, 1, 2, 2], [3, 1, 2, 2, 3] and [1, 2, 2, 3].

Input: arr[] = [1, 1, 1, 1], k = 2
Output: 0
Explanation: There is no subarray having exactly 2 distinct integers.

[Naive Approach] Exploring all subarrays - O(n^2) Time and O(n) Space

The idea is to iterate over all possible subarrays while keeping the count of distinct integers using a hash set. For every subarray, check if the size of hash set is equal to k. If the size of hash set equals k, increment the result by 1. After iterating over all subarrays, return the result.


Output
4

[Expected Approach] Using Sliding Window Technique - O(n) Time and O(n) Space

The idea is similar to the problem Count Subarrays With At Most K Distinct Elements. To find the number of subarrays with exactly k distinct elements, we can use the formula: exactly(k) = atMost(k) - atMost(k - 1).

Count of subarrays with at most k different elements can be easily calculated using sliding window technique. Initialize left = 0 and right = 0 to mark the boundaries of sliding window. Expand the right boundary until distinct element count exceeds k, then shrink the left boundary until the distinct element count becomes <= k. While expanding the window, for each right boundary keep counting the subarrays as (right - left + 1).

The intuition behind (right - left + 1) is that it counts all possible subarrays that end at right and start at any index between left and right. These are valid subarrays because they all contain at most k distinct elements.


Output
4


Comment
Article Tags: