Search code examples
stringin-place

duplicate each space in a given string


I found the following question in many interviews (not my interview).

given a string, you need to replace each space with 2 spaces. you may assume that your string has enough place for adding the required spaces. you need to do it in place, memory allocation is not allowed.

I don't understand how to implement this without override letters.


Solution

  • There's not a lot of context in your question. Let's assume it's a programming interview and you are dealing with a low level language like C or assembler. Let's also assume that the string has a count and/or ends in a null, like 'this is a string\0\0\0\0'

    I would scan the string from beginning to end and count the spaces, let's call that C. Then I would work backward through the string on character at a time moving each character forward by C positions. Each time a space is encountered, copy the space forward by C positions, subtract one from C, and then move the space by C positions. Stop when C is 0.

    Here, nulls/unused are represented by a period.

    this is a string....  C=3
    this is a string..g.
    this is a string.ng.
    this is a stringing.
    this is a strinring.
    this is a stritring.
    this is a strstring.
    this is a st string.
    this is a s  string. C=2
    this is a a  string.
    this is   a  string.
    this iss  a  string.  C=1
    this iis  a  string.  
    this  is  a  string.  C=0