Count of substrings containing exactly K distinct vowels - GeeksforGeeks

29 Dec, 2021
Given string str of size N containing both uppercase and lowercase letters, and an integer K. The task is to find the count of substrings containing exactly K distinct vowels.
Examples:
Input: str = “aeiou”, K = 2Output: 4Explanation: The substrings having two distinct vowels are “ae”, “ei”, “io” and “ou”.
Input: str = “TrueGoik”, K = 3Output: 5Explanation: The substrings are “TrueGo”, “rueGo”, “ueGo”, “eGoi” and “eGoik”.
Approach: The problem can be solved by generating all the substrings. From the generated substrings count the ones having K distinct vowels. Follow the steps mentioned below to implement the approach:
First generate all substrings starting from each index i in range [0, N]
Then for each substring, follow the steps:Keep a hash array to store the occurrences of unique vowels.Check if a new character in the substring is a vowel or not.If it is a vowel, increment its occurrence in the hash and keep a count of distinct vowels foundNow for each substring, if the distinct count of vowels is K, increment the final count.
Keep a hash array to store the occurrences of unique vowels.
Check if a new character in the substring is a vowel or not.
If it is a vowel, increment its occurrence in the hash and keep a count of distinct vowels found
Now for each substring, if the distinct count of vowels is K, increment the final count.
If for any loop to find substrings starting from i, the count of distinct vowels exceeds K, or, the substring length has reached string length, break the loop and look for substrings starting from i+1.
When all the substrings have been considered, print the final count.
Below is implementation of the above approach.
C++
Java
Python3
C#
Javascript
// C++ program to count number of substrings// with exactly k distinct vowels#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');}  int getIndex(char ch){    return (ch - 'A' > 26 ? ch - 'a' :             ch - 'A');}  // Function to count number of substrings// with exactly k unique vowelsint countkDist(string str, int k){    int n = str.length();      // Initialize result    int res = 0;      // Consider all substrings     // beginning with str[i]    for (int i = 0; i < n; i++) {        int dist_count = 0;          // To store count of characters         // from 'a' to 'z'        vector<int> cnt(26, 0);          // Consider all substrings         // between str[i..j]        for (int j = i; j < n; j++) {              // If this is a new vowels            // for this substring,             // increment dist_count.            if (isVowel(str[j])                && cnt[getIndex(str[j])]                 == 0)                dist_count++;              // Increment count of             // current character            cnt[getIndex(str[j])]++;              // If distinct vowels count            // becomes k then increment result            if (dist_count == k)                 res++;              if (dist_count > k)                break;        }    }    return res;}  // Driver codeint main(){    string str = "TrueGoik";    int K = 3;    cout << countkDist(str, K) << endl;    return 0;}
// Java program to count number of substrings// with exactly k distinct vowelsimport java.util.*;public class GFG{    // Function to check whether// a character is vowel or notstatic boolean isVowel(char x){    return (x == 'a' || x == 'e' || x == 'i'             || x == 'o' || x == 'u' || x == 'A'             || x == 'E' || x == 'I'            || x == 'O' || x == 'U');}  static int getIndex(char ch){    return (ch - 'A' > 26 ? ch - 'a' :             ch - 'A');}  // Function to count number of substrings// with exactly k unique vowelsstatic int countkDist(String str, int k){    int n = str.length();      // Initialize result    int res = 0;      // Consider all substrings     // beginning with str[i]    for (int i = 0; i < n; i++) {        int dist_count = 0;          // To store count of characters         // from 'a' to 'z'        int cnt[] = new int[26];        for(int t = 0; t < 26; t++) {            cnt[t] = 0;        }                  // Consider all substrings         // between str[i..j]        for (int j = i; j < n; j++) {              // If this is a new vowels            // for this substring,             // increment dist_count.            if (isVowel(str.charAt(j))                && cnt[getIndex(str.charAt(j))]                 == 0)                dist_count++;              // Increment count of             // current character            cnt[getIndex(str.charAt(j))]++;              // If distinct vowels count            // becomes k then increment result            if (dist_count == k)                 res++;              if (dist_count > k)                break;        }    }    return res;}  // Driver codepublic static void main(String args[]){    String str = "TrueGoik";    int K = 3;    System.out.println(countkDist(str, K));}}  // This code is contributed by Samim Hossain Mondal.
# Python code for the above approach  # Function to check whether# a character is vowel or notdef isVowel(x):    return (x == 'a' or x == 'e' or x == 'i' or x == 'o'            or x == 'u' or x == 'A' or x == 'E' or x == 'I'            or x == 'O' or x == 'U')    def getIndex(ch):    return (ord(ch) - ord('a')) if (ord(ch) - ord('A')) > 26 else (ord(ch) - ord('A'))  # Function to count number of substrings# with exactly k unique vowelsdef countkDist(str, k):    n = len(str)      # Initialize result    res = 0      # Consider all substrings    # beginning with str[i]    for i in range(n):        dist_count = 0          # To store count of characters        # from 'a' to 'z'        cnt = [0] * 26          # Consider all substrings        # between str[i..j]        for j in range(i, n):              # If this is a new vowels            # for this substring,            # increment dist_count.            if (isVowel(str[j]) and cnt[getIndex(str[j])] == 0):                dist_count += 1              # Increment count of            # current character            cnt[getIndex(str[j])] += 1              # If distinct vowels count            # becomes k then increment result            if (dist_count == k):                res += 1              if (dist_count > k):                break    return res  # Driver codes = "TrueGoik"K = 3  print(countkDist(s, K))  # This code is contributed by Saurabh Jaiswal
// C# program to count number of substrings// with exactly k distinct vowelsusing System;class GFG{    // Function to check whether  // a character is vowel or not  static bool isVowel(char x)  {    return (x == 'a' || x == 'e' || x == 'i'             || x == 'o' || x == 'u' || x == 'A'             || x == 'E' || x == 'I'            || x == 'O' || x == 'U');  }    static int getIndex(char ch)  {    return (ch - 'A' > 26 ? ch - 'a' :             ch - 'A');  }    // Function to count number of substrings  // with exactly k unique vowels  static int countkDist(string str, int k)  {    int n = str.Length;      // Initialize result    int res = 0;      // Consider all substrings     // beginning with str[i]    for (int i = 0; i < n; i++) {      int dist_count = 0;        // To store count of characters       // from 'a' to 'z'      int []cnt = new int[26];      for(int t = 0; t < 26; t++) {        cnt[t] = 0;      }        // Consider all substrings       // between str[i..j]      for (int j = i; j < n; j++) {          // If this is a new vowels        // for this substring,         // increment dist_count.        if (isVowel(str[j])            && cnt[getIndex(str[j])]             == 0)          dist_count++;          // Increment count of         // current character        cnt[getIndex(str[j])]++;          // If distinct vowels count        // becomes k then increment result        if (dist_count == k)           res++;          if (dist_count > k)          break;      }    }    return res;  }    // Driver code  public static void Main()  {    string str = "TrueGoik";    int K = 3;    Console.Write(countkDist(str, K));  }}  // This code is contributed by Samim Hossain Mondal.
<script>        // JavaScript code for the above approach          // Function to check whether        // a character is vowel or not        function isVowel(x) {            return (x == 'a' || x == 'e' || x == 'i' || x == 'o'                || x == 'u' || x == 'A' || x == 'E' || x == 'I'                || x == 'O' || x == 'U');        }          function getIndex(ch) {            return ((ch.charCodeAt(0) - 'A'.charCodeAt(0)) > 26 ? (ch.charCodeAt(0) - 'a'.charCodeAt(0)) :                (ch.charCodeAt(0) - 'A'.charCodeAt(0)));        }          // Function to count number of substrings        // with exactly k unique vowels        function countkDist(str, k)        {            let n = str.length;              // Initialize result            let res = 0;              // Consider all substrings             // beginning with str[i]            for (let i = 0; i < n; i++) {                let dist_count = 0;                  // To store count of characters                 // from 'a' to 'z'                let cnt = new Array(26).fill(0)                  // Consider all substrings                 // between str[i..j]                for (let j = i; j < n; j++) {                      // If this is a new vowels                    // for this substring,                     // increment dist_count.                    if (isVowel(str[j])                        && cnt[getIndex(str[j])]                        == 0)                        dist_count++;                      // Increment count of                     // current character                    cnt[getIndex(str[j])]++;                      // If distinct vowels count                    // becomes k then increment result                    if (dist_count == k)                        res++;                      if (dist_count > k)                        break;                }            }            return res;        }          // Driver code        let s = "TrueGoik";        let K = 3          document.write(countkDist(s, K));    // This code is contributed by Potta Lokesh    </script>
  
5
 
Time Complexity: O(N2)Auxiliary Space: O(N2)
 
lokeshpotta20
samim2000
_saurabh_jaiswal
Algo-Geek 2021
substring
Algo Geek
Mathematical
Strings
Strings
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Maximize groups to be formed such that product of size of group with its minimum element is at least K
Maximize partitions that if sorted individually makes the whole Array sorted
Generate string after adding spaces at specific positions in a given String
Count Subarrays with strictly decreasing consecutive elements
Sort given Array in descending order according to highest power of prime factors
Program for Fibonacci numbers
C++ Data Types
Write a program to print all permutations of a given string
Set in C++ Standard Template Library (STL)
Program to find GCD or HCF of two numbers