Remove Vowels from a String — Solution in Python, Java & C++
Remove Vowels from a String solution explained: step-by-step approach, complexity and code in Python, Java, C++ and JavaScript. An easy problem on strings.
Remove Vowels from a String is an easy coding problem on strings, asked in Amazon, TCS, Infosys and Mindtree interviews.
- Difficulty: Easy
- Topics: Strings
- Asked at: Amazon, TCS, Infosys, Mindtree
- Time limit: 2 s
- Memory limit: 256 MB
- Languages: JavaScript, TypeScript, Python, Java, C++, C, C#, Go, Kotlin, Swift, Rust, PHP and Ruby
Problem statement
Given a string s of lowercase English letters, return s with every vowel (a, e, i, o, u) removed.
Example 1
Input: s = "leetcodeisacommunityforcoders"
Output: ltcdscmmntyfrcdrs
Example 2
Input: s = "aeiou"
Output:
Explanation: Every character is a vowel, so nothing remains.
Example 3
Input: s = "rhythm"
Output: rhythm
Constraints
1 <= s.length <= 1000s consists of lowercase English letters.
Hints for Remove Vowels from a String
Hint 1
Build the answer character by character rather than deleting in place.
Hint 2
A five-character membership test is enough — no lookup table needed.
Hint 3
The result may be empty; make sure your code handles that.
How to solve Remove Vowels from a String
A filter over the characters: keep everything that is not one of the five vowels.
Approach
- Walk the string once.
- Append the character to the output unless it is
a,e,i,ooru. - Return the accumulated output.
Why it works
Removal is order-preserving and independent per character, so a single filtering pass is exactly right.
Complexity
- Time —
O(n) - Space —
O(n) for the output
Pitfalls
- Deleting from the string in place while iterating skips characters, because the indices shift under you.
- Repeated string concatenation is O(n²) in some languages — prefer a builder or list-join.
Reference solution
Python
def removeVowels(s: str) -> str:
return ''.join(c for c in s if c not in 'aeiou')Java
public static String removeVowels(String s) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if ("aeiou".indexOf(c) < 0) sb.append(c);
}
return sb.toString();
}C++
string removeVowels(string s) {
string out;
string vowels = "aeiou";
for (char c : s) {
if (vowels.find(c) == string::npos) out += c;
}
return out;
}JavaScript
var removeVowels = function(s) {
let out = "";
for (let i = 0; i < s.length; i++) {
const c = s.charAt(i);
if ("aeiou".indexOf(c) === -1) out += c;
}
return out;
};Also on the editorial tab: C, C#, Go, Kotlin, PHP, Ruby, Rust, Swift, TypeScript.
All 515 strings problems · the whole catalogue
Learn the technique: Strings