Count of K length substrings containing exactly X vowels
Given string str of N characters containing both uppercase and lowercase English alphabets, the task is to find the count of substrings of size K containing exactly X vowels.
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 = “GeeksForGeeks”, K = 2, X = 2
Output: 2
Explanation: The given string only contains 2 substrings of size 2 consisting of 2 vowels. They are “ee” and “ee”.Input: str = “TrueGeek”, K = 3, X = 2
Output: 5
Approach: The given problem can be solved using a sliding window technique by maintaining a window of size K and keeping track of the number of vowels encountered in the current window. If the count of vowels in the current window is equal to X, increment the final required count by 1.
Below is the implementation of the above approach:
C++
// C++ program of the above appraoch#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// K-sized substring having X vowelsint cntSubstr(string str, int K, int X){ // Stores the number of vowels // in the current window int vow = 0; for (int i = 0; i < K; i++) if (isVowel(str[i])) vow++; // Stores the count of K length // substring with X vowels int ans = vow == X ? 1 : 0; for (int i = 1; i < str.length(); i++) { // Remove (i - 1)th character // from the current window vow = isVowel(str[i - 1]) ? vow - 1 : vow; // Insert (i - 1 + K)th character // from the current window vow = isVowel(str[i - 1 + K]) ? vow + 1 : vow; if (vow == X) // Increment answer ans++; } // Return Answer return ans;} // Driver codeint main(void){ string s = "TrueGeek"; int K = 3, X = 2; cout << cntSubstr(s, K, X); return 0;} |
5
Time Complexity: O(N)
Auxiliary space: O(1)

