We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Remove Vowels from a String

Number: 1089

Difficulty: Easy

Paid? Yes

Companies: Amazon


Problem Description

Given a string s, remove all the vowels ('a', 'e', 'i', 'o', 'u') from s and return the resulting string.


Key Insights

  • Use a set of vowels for O(1) membership checks.
  • Iterate through each character of the string and skip vowels.
  • Build the new string with the non-vowel characters.
  • Time complexity is linear with respect to the length of s.

Space and Time Complexity

Time Complexity: O(n), where n is the length of the input string. Space Complexity: O(n), for storing the resulting string.


Solution

We approach the problem by iterating over the input string and checking if each character is a vowel. We use a set (or similar data structure in specific programming languages) to store vowels so that the membership checks can be done in constant time. For each character in the string, if it isn’t in the set of vowels, we append it to our result. Finally, we return the resultant string. Edge cases are inherent since the input string is guaranteed to be between 1 and 1000 characters and contains only lowercase letters.


Code Solutions

def remove_vowels(s):
    # Define vowels as a set for O(1) lookup
    vowels = set("aeiou")
    # Build a list of characters excluding vowels
    result = [char for char in s if char not in vowels]
    # Join the list back into a string and return
    return "".join(result)

# Example usage
if __name__ == "__main__":
    s = "leetcodeisacommunityforcoders"
    print(remove_vowels(s))
← Back to All Questions