Remove Spaces from a String
Problem
Given a string s, return a new string with all space characters removed. Then solve the in-place variant: modify a mutable character array so that the non-space characters are packed at the front, and return the new length.
Input / Output
- Input: string
s(or char array). - Output: the string without spaces (or the new length).
Examples
Example 1
Input: s = "a b c d"
Output: "abcd"
Example 2
Input: s = " "
Output: ""
Example 3
Input: s = "nospaces"
Output: "nospaces"
Constraints
0 <= s.length <= 10^5
Approach
Immutable strings. Filter characters and join: O(n).
In place (two pointers). Keep a write index w = 0. For each read index r, if s[r] != ' ', copy s[r] to s[w] and increment w. At the end w is the new length. This is the same compaction pattern as "Move Zeroes" and "Remove Element", and the interviewer wants to see you recognise it.
Generalisation: remove all whitespace (isspace), or collapse runs of spaces into one (keep a space only if w == 0 or s[w-1] != ' ').
Complexity
- Time: O(n)
- Space: O(n) for the new string; O(1) in place.
Reference solution (Python)
def remove_spaces(s):
return ''.join(c for c in s if c != ' ')
def remove_spaces_inplace(chars):
w = 0
for c in chars:
if c != ' ':
chars[w] = c
w += 1
del chars[w:]
return w
Test cases
| Input | Expected |
|---|---|
"a b c d" | "abcd" |
" " | "" |
"nospaces" | "nospaces" |
list("x y") (in place) | ['x','y'], returns 2 |