This is an interview question Looking for best optimal solution to trim multiple spaces from a string. This operation should be in-place operation.
input =
Keep two indices: The next available spot to put a letter in (say, i
), and the current index you're examining (say, j
).
Just loop over all the characters with j
, and whenever you see a letter, copy it to index i
, then increment i
. If you see a space that was not preceded by a space, also copy the space.
I think this would work in-place...