Count number of substrings
Medium Accuracy: 58.39% Submissions: 4507 Points: 4

Given a string of lowercase alphabets, count all possible substrings (not necessarily distinct) that have exactly k distinct characters. 


Example 1:

Input:
S = "aba", K = 2
Output:
3
Explanation:
The substrings are:
"ab", "ba" and "aba".

Example 2:

Input: 
S = "abaaca", K = 1
Output:
7
Explanation:
The substrings are:
"a", "b", "a", "aa", "a", "c", "a". 


Your Task:
You don't need to read input or print anything. Your task is to complete the function substrCount() which takes the string S and an integer K as inputs and returns the number of substrings having exactly K distinct characters.


Expected Time Complexity: O(|S|).
Expected Auxiliary Space: O(1).


Constraints:
1 ≤ |S| ≤ 105
1 ≤ K ≤ 26

We are replacing the old Disqus forum with the new Discussions section given below.
Click here to view old Disqus comments.


to report an issue on this page.

Editorial

We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial?

Yes

All Submissions

My Submissions:

Login to access your submissions.

Count number of substrings

Output Window