Count of substrings containing exactly K vowels
Given string str containing both uppercase and lowercase letters, and an integer K. The task is to find the count of substrings containing exactly K vowels (maybe repetitive).
Examples:
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.
Input: str = “aeiou”, K = 2
Output: 4
Explanation: The substrings are “ae”, “ei”, “io”, “ou”.Input: str = “TrueGeek”, K = 3
Output: 5
Explanation: All such possible substrings are:
“TrueGe”, “rueGe”, “ueGe”, “eGee”, “eGeek”.
Approach: To solution of this problem is based on greedy approach. Generate all substrings and for each substring check the count of vowels. Follow the steps mentioned below.
- Generate all the substrings. For each substring do the following
- Store the count of occurrences of vowels.
- Check if a new character in the substring is a vowel or not.
- If it is a vowel, increment count of vowels found
- Now for each substring, if the count of vowels is K, increment the final count.
- Return the final count as the required answer at the end.
Below is the implementation of the above code.
C++
// C++ code to implement above approach#include <bits/stdc++.h>using namespace std; #define MAX 128 // Function to check whether// a character is vowel or notbool isVowel(char x){ return (x == 'a' || x == 'e' || x == 'i' || x == 'o' || x == 'u' || x == 'A' || x == 'E' || x == 'I' || x == 'O' || x == 'U');} // Function to find the count of// substring with k vowelsint get(string str, int k){ int n = str.length(); // Stores the count of // substring with K vowels int ans = 0; // Consider all substrings // beginning with str[i] for (int i = 0; i < n; i++) { int count = 0; // Consider all substrings // between [i, j] for (int j = i; j < n; j++) { // If this is a vowel, for this // substring, increment count. if (isVowel(str[j])) { count++; } // If vowel count becomes k, // then increment final count. if (count == k) { ans++; } if (count > k) break; } } return ans;} // Driver codeint main(void){ string s = "aeiou"; int K = 2; cout << get(s, K); return 0;} |
4
Time Complexity: O(N2) where N is the length of the string.
Auxiliary Space: O(1)

