![]() |
VOOZH | about |
Given a string str containing lowercase alphabets, the task is to count 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: str = "aeoibsddaaeiouudb"
Output: 4
Explanation: The 4 distinct substrings containing all the vowels in order are "aaeiouu", "aeiouu", "aeiou", and "aaeiou".
Input: str = "aeoisbddiouuaedf"
Output: 1
Explanation: Only one substring "iouuae" contains all the vowels in order.
Input: str = "aeouisddaaeeiouua"
Output: 9
Explanation: There are 9 distinct substrings containing all vowels in order in the given string.
Table of Content
The idea is to iterate over all possible substrings of the input string and check if each substring contains all the vowels ('a', 'e', 'i', 'o', 'u'). For each substring, a count is maintained for each vowel. If all vowels are found in a substring, it is considered valid, and the count is incremented. The process stops as soon as a consonant is encountered in a substring, as only vowel-only substrings are valid.
Below is the implementation of the above approach:
4
Time Complexity: O(n^2), for generating all substrings and constant time for checking vowels.
Auxiliary Space: O(1), for tracking vowels and substring building.
The idea is to use a sliding window approach, the sliding window is maintained using two pointers and a frequency map to track the counts of vowels within the window.
- As we iterate through the string, we check if each character is a vowel and update its count in the frequency map.
- If a vowel is found, we track how many unique vowels are present in the current window. To ensure the window is valid, we adjust its size by moving the start pointer when duplicate vowels are encountered.
- If all vowels are present, the count is updated by adding the possible valid substrings that can end at the current position.
- The process resets whenever a non-vowel character is encountered, starting a new window from the next position.
- This ensures we efficiently count all valid substrings containing all vowels, avoiding unnecessary processing of invalid substrings.
Below is the implementation of the above approach:
4
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).