Problem of the day
You are given a string 'str' of lowercase alphabets and an integer 'k' .
Your task is to return the count all the possible substrings that have exactly 'k' distinct characters.
For example:
'str' = abcad and 'k' = 2.
We can see that the substrings {ab, bc, ca, ad} are the only substrings with 2 distinct characters.
Therefore, the answer will be 4.
Input format :
The first line contains a string ‘str’.
The second line contains a single integer 'k'.
Output format :
The output contains a single integer which is the count of all possible substrings having exactly 'k' distinct characters.
Note:
You don’t have to print anything. Just implement the given function.
aacfssa
3
5
Given 'str' = “aacfssa”. We can see that the substrings with only 3 distinct characters are {aacf, acf, cfs, cfss, fssa}.
Therefore, the answer will be 5.
qffds
4
1
1 <= |str| <= 10^5
1 <= k <= 26
Time Limit: 1 second
Can you check for all the possible substrings?
The idea is to check for all the substrings of the given string and then check for each substring whether it contains exactly K different characters or not.
O(N ^ 3), where ‘N’ denotes the length of the given string.
We are calculating all possible substrings of the string and then we are calculating the count of characters in each substring. So, the time complexity will be O(N ^ 3)(for calculating every substring) + O(N)(for counting) = O(N ^ 3).
O(N), where ‘N’ denotes the length of the given string.
Since we are using a hashmap for storing the string characters, the net space complexity will be O(N).