Problem Description
Given a string composed solely of English vowels, a substring is considered beautiful if it contains all 5 vowels (‘a’, ‘e’, ‘i’, ‘o’, ‘u’) at least once and they appear in alphabetical order (i.e., all ‘a’s come before any ‘e’s, etc.). The task is to determine the length of the longest contiguous beautiful substring within the string. If no such substring exists, return 0.
Key Insights
- The substring must include the vowels in the specific order: a, e, i, o, u.
- A sliding window or two-pointer approach can efficiently traverse the string.
- If there is any violation of the order, reset the tracking and possibly start a new substring from the current character.
- Ensure that the substring actually contains all vowels before updating the maximum length.
Space and Time Complexity
Time Complexity: O(n), where n is the length of the string, as each character is processed once.
Space Complexity: O(1), using only constant extra space for tracking variables and states.
Solution
The solution involves iterating through the string while maintaining the current substring's length, the current expected vowel (tracked by an index for "aeiou"), and a flag array to indicate if each vowel has been encountered at least once. When a character violates the current order, check if the substring so far is beautiful and then either reset the state (or possibly start with the current character if it’s 'a'). Update the maximum length accordingly.