17. Remove Spaces from a String

Difficulty:EasyPattern:String Traversal / FilteringTime:O(n)Space:O(n)

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:

  1. Create an empty result string.
  2. Visit each character.
  3. If the character is not a space, append it to the result.
  4. 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.