Leetcode #1839: Longest Substring Of All Vowels in Order
In this guide, we solve Leetcode #1839 Longest Substring Of All Vowels in Order in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
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.
Quick Facts
- Difficulty: Medium
- Premium: No
- Tags: String, Sliding Window
Intuition
We are looking for a contiguous region that satisfies a constraint, which is a classic sliding-window signal.
Expanding and shrinking the window lets us maintain validity without restarting the scan.
Approach
Grow the window with a right pointer, and shrink from the left only when the constraint is violated.
Track the best window as you go to keep the solution linear.
Steps:
- Expand the right end of the window.
- While invalid, move the left end to restore constraints.
- Update the best window found.
Example
Input: word = "aeiaaioaaaaeiiiiouuuooaauuaeiu"
Output: 13
Explanation: The longest beautiful substring in word is "aaaaeiiiiouuu" of length 13.
Python Solution
class Solution:
def longestBeautifulSubstring(self, word: str) -> int:
arr = []
n = len(word)
i = 0
while i < n:
j = i
while j < n and word[j] == word[i]:
j += 1
arr.append((word[i], j - i))
i = j
ans = 0
for i in range(len(arr) - 4):
a, b, c, d, e = arr[i : i + 5]
if a[0] + b[0] + c[0] + d[0] + e[0] == "aeiou":
ans = max(ans, a[1] + b[1] + c[1] + d[1] + e[1])
return ans
Complexity
The time complexity is , and the space complexity is . The space complexity is .
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.