17. Remove Spaces from a String
Given a string, create a new string with all space characters removed.
How It Works & Algorithmic Design
Traverse the string and keep only non-space characters:
- Create an empty result string.
- Visit each character.
- If the character is not a space, append it to the result.
- Return the resulting string.
Why This Approach Works Best
Every character must be examined, giving $O(n)$ time. A new string is produced, requiring $O(n)$ output space.
Example Walkthrough
Input:
"hello world from JS"The string contains spaces between words.
Filtering:
"hello" + "world" + "from" + "JS"Space characters are skipped.
Output:
"helloworldfromJS"All spaces have been removed.
Answer: Remove spaces
function removeSpaces(str) {
let result = '';
for (const char of str) {
if (char !== ' ') result += char;
}
return result;
}💡 Build a new string containing only non-space characters.
Key Takeaways
- This is a filtering problem over characters.
- Characters that do not satisfy the condition are skipped.
- A new string requires additional output space.