A substring is a contiguous (non-empty) sequence of characters within a string.
A vowel substring is a substring that only consists of vowels ('a', 'e', 'i', 'o', and 'u') and has all five vowels present in it.
Given a string word, return the number of vowel substrings in word.
Example 1:
Input: word = "aeiouu" Output: 2 Explanation: The vowel substrings of word are as follows (underlined): - "aeiouu" - "aeiouu"
Example 2:
Input: word = "unicornarihan" Output: 0 Explanation: Not all 5 vowels are present, so there are no vowel substrings.
Example 3:
Input: word = "cuaieuouac" Output: 7 Explanation: The vowel substrings of word are as follows (underlined): - "cuaieuouac" - "cuaieuouac" - "cuaieuouac" - "cuaieuouac" - "cuaieuouac" - "cuaieuouac" - "cuaieuouac"
Constraints:
1 <= word.length <= 100word consists of lowercase English letters only.This approach involves iterating over all possible substrings of the given string and checking if each substring contains all the vowels ('a', 'e', 'i', 'o', 'u'). This is a straightforward method but not optimized due to the nested loop structure.
The solution in C involves two nested loops to iterate over all possible substrings. Each substring is then checked for the presence of all five vowels using the helper function 'containsAllVowels'. The 'isVowel' function helps in determining if a character is part of the vowels.
C++
Java
Python
C#
JavaScript
Time Complexity: O(n^3) due to the triply nested loop structure.
Space Complexity: O(1) as only a fixed-size array is used to check vowels.
This approach leverages a sliding window mechanism to efficiently find substrings containing all vowels. By keeping track of the vowel count, the window can be expanded and contracted to find matches, significantly reducing unnecessary duplicate work.
The C implementation uses a sliding window to efficiently manage the range in which all vowels appear. When a non-vowel is encountered, the state is reset, improving performance over analyzing static substrings.
C++
Java
Python
C#
JavaScript
Time Complexity: O(n) compared to the traditional O(n^3).
Space Complexity: O(1).
| Approach | Complexity |
|---|---|
| Brute Force Approach | Time Complexity: O(n^3) due to the triply nested loop structure. |
| Sliding Window Approach | Time Complexity: O(n) compared to the traditional O(n^3). |
L7. Number of Substrings Containing All Three Characters | 2 Pointers and Sliding Window Playlist • take U forward • 117,863 views views
Watch 9 more video solutions →Practice Count Vowel Substrings of a String with our built-in code editor and test cases.
Practice on FleetCodePractice this problem
Open in Editor