Find all substrings containing exactly K unique vowels - GeeksforGeeks

28 Feb, 2022
Given string str of length N containing both uppercase and lowercase letters, and an integer K. The task is to find all substrings containing exactly K distinct vowels.
Examples:
Input:  str = “aeiou”, K = 2Output: “ae”, “ei”, “io”, “ou”Explanation: These are the substrings containing exactly 2 distinct vowels.
Input: str = “TrueGeek”, K = 3Output: “”Explanation: Though the string has more than 3 vowels but there is not three unique vowels.So the answer is empty.
Input: str = “TrueGoik”, K = 3Output: “TrueGo”, “rueGo”, “ueGo”, “eGoi”, “eGoik”
Approach: This problem can be solved by greedy approach. Generate the substrings and check for every substring. Follow the steps mentioned below to solve the problem:
First generate all substrings starting from each index i in range 0 to N.
Then for each substring: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, print the substring.
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, print the substring.
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.
Below is the implementation of the above approach.
C++
Java
Python3
C#
Javascript
// C++ program to find all 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 find all substrings// with exactly k unique vowelsvoid countkDist(string str, int k){    int n = str.length();       // 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 vowel            // 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 print the            // substring.            if (dist_count == k) {                cout << str.substr(i, j - i + 1) << endl;            }             if (dist_count > k)                break;        }    }} // Driver codeint main(){    string str = "TrueGoik";    int K = 3;    countkDist(str, K);    return 0;}
// Java program to find all subStrings with// exactly k distinct vowelsimport java.util.*; class GFG{   static final int MAX = 128;   // Function to check whether  // a character is vowel or not  static 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 find all subStrings  // with exactly k unique vowels  static void countkDist(String str, int k)  {    int n = str.length();     // 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];       // Consider all subStrings      // between str[i..j]      for (int j = i; j < n; j++) {        String print  = new String(str);        // If this is a new vowel        // 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 print the        // subString.        if (dist_count == k) {          System.out.print(print.substring(i, j +1) +"\n");        }         if (dist_count > k)          break;      }    }  }   // Driver code  public static void main(String[] args)  {    String str = "TrueGoik";    int K = 3;    countkDist(str, K);  }} // This code is contributed by Rajput-Ji
# python3 program to find all substrings with# exactly k distinct vowelsMAX = 128 # 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):    if ord(ch) - ord('A') > 26:        return ord(ch) - ord('a')    else:        return ord(ch) - ord('A') # Function to find all substrings# with exactly k unique vowelsdef countkDist(str, k):    n = len(str)     # Consider all substrings    # beginning with str[i]    for i in range(0, n):        dist_count = 0         # To store count of characters        # from 'a' to 'z'        cnt = [0 for _ in range(26)]         # Consider all substrings        # between str[i..j]        for j in range(i, n):             # If this is a new vowel            # 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 print the            # substring.            if (dist_count == k):                print(str[i:i+j - i + 1])             if (dist_count > k):                break # Driver codeif __name__ == "__main__":     str = "TrueGoik"    K = 3    countkDist(str, K)     # This code is contributed by rakeshsahni
// C# program to find all 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 find all substrings  // with exactly k unique vowels  static void countkDist(string str, int k)  {    int n = str.Length;     // 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];       // Consider all substrings      // between str[i..j]      for (int j = i; j < n; j++) {         // If this is a new vowel        // 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 print the        // substring.        if (dist_count == k) {          Console.WriteLine(            str.Substring(i, j - i + 1));        }         if (dist_count > k)          break;      }    }  }   // Driver code  public static void Main()  {    string str = "TrueGoik";    int K = 3;    countkDist(str, K);  }} // This code is contributed by ukasp.
<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 find all substrings      // with exactly k unique vowels      function countkDist(str, k) {          let n = str.length;           // 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 vowel                  // 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 print the                  // substring.                  if (dist_count == k) {                      document.write(str.slice(i, i + j - i + 1) + '<br>');                  }                   if (dist_count > k)                      break;              }          }      }       // Driver code       let s = "TrueGoik";      let K = 3       countkDist(s, K); // This code is contributed by Potta Lokesh  </script>
  
TrueGo
rueGo
ueGo
eGoi
eGoik
 
Time Complexity: O(N2)Auxiliary Space: O(N2) to store the resulting substrings
 
lokeshpotta20
rakeshsahni
ukasp
Rajput-Ji
Algo-Geek 2021
substring
Algo Geek
Hash
Mathematical
Strings
Hash
Strings
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Maximize partitions that if sorted individually makes the whole Array sorted
Day-Stout-Warren algorithm to balance given Binary Search Tree
Count Subarrays with strictly decreasing consecutive elements
Find Characteristic Polynomial of a Square Matrix
Find all Palindrome Strings in given Array of strings
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
Internal Working of HashMap in Java
Hashing | Set 1 (Introduction)
Count pairs with given sum
Hashing | Set 3 (Open Addressing)