![]() |
VOOZH | about |
Given a string s containing lowercase alphabets, the task is to print the sub-strings that contain all the vowels at-least one time and there are no consonants (non-vowel characters) present in the sub-strings.
Examples:
Input: s = "aeoibsddaaeiouudb"
Output: ["aaeiouu", "aeiouu", "aeiou", "aaeiou"]
Explanation: The 4 distinct substrings containing all the vowels in order are "aaeiouu", "aeiouu", "aeiou", and "aaeiou".
Input: s = "aeoisdiouuae"
Output: ["iouuae"]
Explanation: Only one substring "iouuae" contains all the vowels in order.
Table of Content
The idea behind this code is to find all substrings of the input string that contain all the vowels ('a', 'e', 'i', 'o', 'u'). The approach is to iterate over all possible starting points of substrings in the given string. For each starting point, we explore all possible ending points to form substrings. As we form each substring, we check whether all its characters are vowels, breaking the loop immediately if a consonant is encountered since only vowel-only substrings are valid. While processing each valid substring, we track the count of each vowel. If all vowels are present in the current substring, we add it to the result. Finally, we return the result containing all valid substrings
Below is the implementation of the above approach:
aaeiou aaeiouu aeiou aeiouu
Time Complexity: O(n^2), for generating all substrings and checking vowels.
Auxiliary Space: O(1), as apart from input and output we are using constant extra space.
The idea is to use a sliding window approach to find substrings containing all the vowels ('a', 'e', 'i', 'o', 'u'). The sliding window dynamically adjusts by maintaining a frequency map of vowels within the window. As we traverse the string, we check if the current character is a vowel and update the frequency map while counting unique vowels in the window. When all vowels are present, we add valid substrings ending at the current position to the result. If a non-vowel character is encountered, the window is reset, and we start from the next position. Throughout, the window is adjusted to remove duplicate vowels while ensuring the substring remains valid. This process continues until all possible substrings are evaluated.
Below is the implementation of the above approach:
aeiou aaeiou aeiouu aaeiouu
Time Complexity: O(n), as we are iterating through the string once, and each character is processed in constant time.
Auxiliary Space: O(1), since we are using a fixed-size frequency map (for vowels).