Substring with Maximum Number of Vowels of Given Length (k)

You are given a string of some length (n); the problem is finding a substring of some given length (k) that contains the maximum number of vowels in linear time.

The substring can start from any position in the string, and the vowels can be in any order. If two substrings have the same number of vowels count, the first substring should be returned.

Example 1:

Example 2:

Example 3:

Constraints:

  • The input will consist of a string and integer k.
  • All the letters in the input will be in lowercase.
  • The length of k will be between 1 and len(string)

Python program to find a substring with the maximum number of vowels:

The program can be summarized as follows:

  1. Count the number of vowels in the substring of length k starting from 0: s[0:k]
  2. Check if the count is greater than zero, indicating that the substring contains some vowels.
  3. Store the substring as answer = s[0:k] and make the max_vowel_count = count.
  4. Initialize two variables, i = 0 and j = k.
  5. Check if s[i] is a vowel or not. If yes, then count -= 1
  6. Check if s[j] is a vowel or not. If yes, then count += 1
  7. Check if the count is greater than max_vowel_count or not. If yes, meaning s[i] was a consonant, and s[j] was a vowel.
  8. Update the answer = s[i+1, j+1] and max_vowel_count = count
  9. Repeat steps 5 to 8 until all the letters have been processed.
  10. Return the answer.

Output

Enter a string: agfshuekjiylsk
Enter the length of the substring: 3
Output: hue

Enter a string: kwytpqjz
Enter the length of the substring: 5
Output: No Substring Found!

Time Complexity - O(n): This is because the program iterates over the given string, and n represents the size of the string.

Space Complexity - O(n): No extra space is needed.

C++ program to find a substring with the maximum number of vowels:

Output

Enter a string: deriikoiuaplo
Enter the length of the substring: 5
Output: iikoi

C program to find a substring with the maximum number of vowels:

Output

Enter a string: usipaotutpsythsuiaonhuaisre
Enter the length of the substring: 7
Output: uiaonhu

Java program to find a substring with the maximum number of vowels:

Output

Enter a string: aoabdiewbiieazodgagji
Enter the length of the substring: 5
Output: biiea