Remove All Spaces from a String
Solve this ProblemEasy5 min
Topics
BasicsStrings
Companies
TCSInfosysWipro
Given a string
text, return it with every space removed — at the start, the end and in the middle.
Removing characters is a filter: walk through the input and copy only what you want to keep. Unlike trimming, which only looks at the two ends, this visits every character. In C it introduces a write indexWrite IndexA separate position that marks where the next kept item is written, so filtered output has no gaps. that moves more slowly than the read index.
Test Case 1:
Input:text = "a b c"
Output:"abc"
Explanation:Every space is dropped, wherever it is.
Test Case 2:
Input:text = "nospace"
Output:"nospace"
Explanation:Nothing to remove.
Constraints
- ◆
1 ≤ text.length ≤ 1000 - ◆
text contains printable ASCII characters
Try the Dry Run
Approach & Solutions
Copy Every Non-Space CharacterGood
Build the result character by character, copying everything except spaces. In C, a write index pos tracks where the next kept character goes, so the result is packed with no gaps.
Time
O(n)Space
O(n)Java
class Solution {
public String removeSpaces(String text) {
StringBuilder result = new StringBuilder();
for (char ch : text.toCharArray()) {
if (ch != ' ') {
result.append(ch);
}
}
return result.toString();
}
}Built-in ReplaceOptimal
Replace every space with nothing: replace(" ", "") in Java and Python, and the erase–remove idiom in C++. JavaScript splits the text on " " and joins the pieces back with "" — this works in every JavaScript version, while replaceAll only exists in newer ones. C keeps the copying loop.
Time
O(n)Space
O(n)Java
class Solution {
public String removeSpaces(String text) {
return text.replace(" ", "");
}
}