1. Built-In Functions

class Solution:
    def removeVowels(self, s: str) -> str:
        return re.sub(r"[aeiou]", "", s)

Time & Space Complexity

  • Time complexity: O(n)O(n)
  • Space complexity: O(n)O(n)

Where nn is the length of the string ss.


2. Hash Set

class Solution:
    def removeVowels(self, s: str) -> str:
        vowels = set("aeiou")
        res = []
        for c in s:
            if c not in vowels:
                res.append(c)
        return "".join(res)

Time & Space Complexity

  • Time complexity: O(n)O(n)
  • Space complexity:
    • O(1)O(1) extra space.
    • O(n)O(n) space for the output string.

Where nn is the length of the string ss.


3. Iteration

class Solution:
    def removeVowels(self, s: str) -> str:
        def isVowel(c):
            return c == "a" or c == "e" or c == "i" or c == "o" or c == "u"

        res = []
        for c in s:
            if not isVowel(c):
                res.append(c)
        return "".join(res)

Time & Space Complexity

  • Time complexity: O(n)O(n)
  • Space complexity:
    • O(1)O(1) extra space.
    • O(n)O(n) space for the output string.

Where nn is the length of the string ss.


4. Two Pointers (In-Place)

class Solution:
    def removeVowels(self, s: str) -> str:
        chars = list(s)
        j = 0
        for i in range(len(chars)):
            if chars[i] not in "aeiou":
                chars[j] = chars[i]
                j += 1
        return "".join(chars[:j])

Time & Space Complexity

  • Time complexity: O(n)O(n)
  • Space complexity: O(n)O(n) for the character array.

Where nn is the length of the string ss.