AlgoMaster Logo

Replace All Spaces with a Character

Last Updated: June 7, 2026

easy
2 min read

Understanding the Problem

Produce a new string identical to s, except every space is swapped for ch. Every other character keeps its original value and position.

If the input has no spaces, the output equals the input. If the input is empty, the output is empty too.

The transformation is a one-to-one mapping. Positions never shift, because you swap one character for another rather than inserting or deleting anything. Only the spaces change, so the result has the same length as the input.

Key Constraints:

  • 0 <= s.length <= 1000 → The string can be empty, in which case the result is also empty. The code must handle that without indexing into anything.
  • Single replacement character → Each space becomes exactly one character, so the length never changes.

Approach 1: Linear Scan and Build

Intuition

Spaces can sit anywhere, so inspect each character. If the current character is a space, append ch. Otherwise, append the original character unchanged. The decision is local, so it never depends on what came before or after.

Build the result into a growable buffer rather than repeatedly concatenating onto a string, since some languages copy the entire string on every concatenation. By the end, the buffer holds the fully transformed string.

Algorithm

  1. Create an empty, growable buffer to hold the result.
  2. Loop over every character in the input string.
  3. If the current character is a space, append ch to the buffer.
  4. Otherwise, append the current character to the buffer.
  5. After the loop, convert the buffer to a string and return it.

Example Walkthrough

1Index 0 is 'a', not a space. Keep it. result = "a".
0
i
a
1
2
b
3
4
c
1/5

Take s = "a b c" with ch = '_'. Index 0 is a, not a space, so it is copied and the result is "a". Index 1 is a space, so _ is appended, giving "a_". Index 2 is b, copied to give "a_b". Index 3 is a space, so _ is appended, giving "a_b_". Index 4 is c, copied to give "a_b_c". The pass is complete.

Each step only looks at the single character under the current index, with no need to look ahead or backtrack. The buffer grows by exactly one character per step, so after processing all five input characters it holds five output characters.

0
a
1
_
2
b
3
_
4
c
result

Code