Longest Substring Of All Vowels in Order - Problem

A string is considered beautiful if it satisfies the following conditions:

  • Each of the 5 English vowels ('a', 'e', 'i', 'o', 'u') must appear at least once in it.
  • The letters must be sorted in alphabetical order (i.e. all 'a's before 'e's, all 'e's before 'i's, etc.).

For example, strings "aeiou" and "aaaaaaeiiiioou" are considered beautiful, but "uaeio", "aeoiu", and "aaaeeeooo" are not beautiful.

Given a string word consisting of English vowels, return the length of the longest beautiful substring of word. If no such substring exists, return 0.

A substring is a contiguous sequence of characters in a string.

Input & Output

Example 1 — Basic Beautiful Substring
$ Input: word = "aeiouaaaeiou"
Output: 13
💡 Note: The longest beautiful substring is "aeiouaaaeiou" with length 13. It contains all vowels a,e,i,o,u in order.
Example 2 — Multiple Beautiful Substrings
$ Input: word = "aeiou"
Output: 5
💡 Note: The entire string "aeiou" is beautiful with length 5. It contains each vowel exactly once in alphabetical order.
Example 3 — No Beautiful Substring
$ Input: word = "uaeio"
Output: 0
💡 Note: No beautiful substring exists because the vowels are not in alphabetical order.

Constraints

  • 1 ≤ word.length ≤ 5 × 104
  • word consists of only English vowels

Visualization

Tap to expand
Longest Beautiful Substring - State Machine INPUT word = "aeiouaaaeiou" a e i o u a a a e i o u indices: 0-11 (length 12) State Machine States: a e i o u (FINAL) Beautiful: all vowels in order a --> e --> i --> o --> u count=0, maxLen=0, state=0 ALGORITHM STEPS 1 Initialize Tracking count=0, maxLen=0 vowelCount=0 (states 1-5) 2 State Transitions If char == current vowel: count++ (stay in state) If char == next vowel: move to next state 3 Check Valid Sequence When state reaches 'u': update maxLen if count is greater 4 Reset on Invalid If char breaks order: if char=='a': reset state else: count=0, state=0 Processing Example: "aeiou" len=5 [valid] "aaaeiiou" extends len=8 Full string: len=12 FINAL RESULT Longest Beautiful Substring Found: "aeiouaaaeiou" Wait - checking both substrings Substring Analysis: "aeiou" len = 5 "aaaeiou" len = 7 Combined valid sequence: "aeiouaaaeiou" (extended) OUTPUT 13 OK - Maximum length found! All 5 vowels in order Key Insight: The State Machine approach tracks transitions between vowel states (a-->e-->i-->o-->u). A valid "beautiful" substring must visit all 5 states in order. We maintain current length and update maxLen only when reaching the final 'u' state. Reset on invalid transitions. TutorialsPoint - Longest Substring Of All Vowels in Order | State Machine Approach
Asked in
Google 12 Facebook 8 Amazon 6
23.0K Views
Medium Frequency
~25 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen