Trim Trailing Vowels Problem
#3856
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 3856.
You are given a string s that consists of lowercase English letters.
Return the string obtained by removing all trailing vowels from s.
The vowels consist of the characters 'a', 'e', 'i', 'o', and 'u'.
Example 1:
Input: s = "idea"
Output: "id"
Explanation:
Removing "idea", we obtain the string "id".
Example 2:
Input: s = "day"
Output: "day"
Explanation:
There are no trailing vowels in the string "day".
Example 3:
Input: s = "aeiou"
Output: ""
Explanation:
Removing "aeiou", we obtain the string "".
Constraints:
1 <= s.length <= 100sconsists of only lowercase English letters.
Solution
Approach: Scan from the End
Start at the last character and move left while the character is a vowel. Everything up to and including the first non-vowel found is kept; if the string is all vowels the result is empty.
Complexity: O(n) time and O(1) extra space.
class Solution:
def trimTrailingVowels(self, s: str) -> str:
i = len(s) - 1
while i >= 0 and s[i] in "aeiou":
i -= 1
return s[: i + 1]