Remove Vowels from a String Problem
#1119
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 1119.
Given a string s, remove the vowels 'a', 'e', 'i', 'o', and 'u' from it, and return the new string.
Example 1:
Input: s = "leetcodeisacommunityforcoders"
Output: "ltcdscmmntyfrcdrs"
Example 2:
Input: s = "aeiou"
Output: ""
Constraints:
1 <= s.length <= 1000sconsists of only lowercase English letters.
Solution
Approach: One Pass
Go through s once and keep every character that is not one of a, e, i, o, u. Collect the kept characters in a string builder (or a list joined at the end) rather than adding to an immutable string one character at a time, which can copy the whole string on every step in some languages.
If s has only vowels, nothing is kept and the answer is the empty string.
Complexity: O(n) time, and O(n) space for the answer.
class Solution:
def removeVowels(self, s: str) -> str:
return "".join(c for c in s if c not in "aeiou")