# Count number of substrings with exactly k distinct characters in C++

Given a string str[] containing lowercase alphabets only and an integer value k. The goal is to find the number of possible substrings of str that have exactly k distinct elements.

For Example

## Input

str= ”pqr” k=2

## Output

Count of number of substrings with exactly k distinct characters are: 2

## Explanation

The substrings having exactly 2 distinct elements are: “pq”, “qr”.

## Input

str= ”stristr” k=4

## Output

Count of number of substrings with exactly k distinct characters are: 10

## Explanation

The substrings having exactly 2 distinct elements are:
“stri”, “tris”, “rist”, “istr”, “stris”, “trist”, “ristr”, “strist”, “tristr”, “stristr”.

Approach used in the below program is as follows

In this approach we will an array array to store the frequency of english alphabets inside the string str. Now traverse str using two for loops, if for substring, each character is occurring once then increment count of unique characters, at the end of that substring if that count is equal to k then increment count of substrings following the given conditions.

• Take a string str as input.

• Take an integer k with positive value.

• Function substring_k(string str, int length, int k) takes str and k and returns count of the number of substrings with exactly k distinct characters.

• Take the initial count as 0.

• Take frequency array array.

• Traverse str using two for loops from i=0 to i<lenght and j=i to j<lenght.

• Take temp as count of unique elements in substring str[i to j].

• If array[str[j] − 'a']==0 then this character str[j] has occurred first time in this substring. So increment temp.

• Now increment count of current character using array[str[j] − 'a']++.

• If temp is equal to k then increment count.

• If temp is more than k then stop commuting further and break the loop.

• At the end of all loops return count as result.

## Example

Live Demo

#include<bits/stdc++.h>
using namespace std;
int substring_k(string str, int length, int k){
int count = 0;
int array;
for (int i = 0; i < length; i++){
int temp = 0;
memset(array, 0, sizeof(array));
for (int j = i; j < length; j++){
if(array[str[j] − 'a'] == 0){
temp++;
}
array[str[j] − 'a']++;
if (temp == k){
count++;
}
if(temp > k){
break;
}
}
}
return count;
}
int main(){
string str = "abc";
int length = str.length();
int k = 1;
cout<<"Count of number of substrings with exactly k distinct characters are: "<<substring_k(str, length, k);
return 0;
}

## Output

If we run the above code it will generate the following output −

Count of number of substrings with exactly k distinct characters are: 3