#1839

Longest Substring Of All Vowels in Order

Medium
StringSliding WindowSliding WindowTwo Pointers
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

The optimal solution uses a sliding window approach to efficiently find the longest beautiful substring. By maintaining a window of characters that satisfies the conditions, we can avoid generating all substrings and instead focus on extending or shrinking our window based on the characters we encounter.

⚙️

Algorithm

4 steps
  1. 1Step 1: Initialize two pointers (left and right) to the start of the string.
  2. 2Step 2: Expand the right pointer to include characters until the substring is no longer beautiful.
  3. 3Step 3: If the substring is beautiful, update the maximum length and try to expand the right pointer further.
  4. 4Step 4: If it becomes un-beautiful, move the left pointer to shrink the window until it becomes beautiful again.
solution.py14 lines
1def longestBeautifulSubstring(word):
2    vowels = 'aeiou'
3    left = 0
4    max_length = 0
5    count = {v: 0 for v in vowels}
6    for right in range(len(word)):
7        if word[right] in count:
8            count[word[right]] += 1
9            while count['a'] > count['e'] or count['e'] > count['i'] or count['i'] > count['o'] or count['o'] > count['u']:
10                count[word[left]] -= 1
11                left += 1
12            if all(count[v] > 0 for v in vowels):
13                max_length = max(max_length, right - left + 1)
14    return max_length

Complexity note: The time complexity is O(n) because we make a single pass through the string with the two pointers. The space complexity is O(1) since we only use a fixed-size array to count the vowels.

  • 1A substring must contain all vowels in order, which can be tracked using a sliding window.
  • 2The problem can be efficiently solved using a two-pointer technique to maintain a valid substring.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.