#3856
Trim Trailing Vowels
EasyStringString ManipulationTwo Pointers
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
We can efficiently find the last non-vowel character by scanning the string from the end, making it a linear time solution.
⚙️
Algorithm
3 steps- 1Step 1: Initialize a pointer at the end of the string.
- 2Step 2: Move the pointer left until a non-vowel is found.
- 3Step 3: Return the substring from the start to the pointer index.
solution.py5 lines
1def trim_trailing_vowels(s):
2 i = len(s) - 1
3 while i >= 0 and s[i] in 'aeiou':
4 i -= 1
5 return s[:i + 1]ℹ
Complexity note: The complexity is O(n) because we traverse the string once, and O(n) space is used for the substring.
- 1Trailing vowels can be efficiently trimmed by scanning from the end.
- 2Understanding string manipulation is crucial for optimizing performance.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.