3

I have just started reading Cracking the Coding Interview. One of the problems (specifically 1.4) after solving and then looking at the answer made me question the way it is done and decided to post it up here to see if I am missing something.

Here is the problem:

Write a method to replace all spaces in a string with '%20'. You may assume that the string has sufficient space at the end of the string to hold the additional characters, and that you are given the 'true' length of the string. (Note: if implementing in Java, please use a character array so that you can perform this operation in place.)

Example: Input "Mr John Smith ", 13 Output "Mr%20John%20Smith"

Author's solution:

public void replaceSpaces(char[] str, int length)
{
    int spaceCount = 0, newLength, i;
    for(i=0; i<length; i++)
    {
        if (str[i] == '')
        {
           spaceCount++;
        }
    }  
    // ...  
}

I put ... because the rest is irrelevant to my question.

Why loop around to find the spaceCount if you can just compute (str.length - length) / 2?

3

The definition you posted says:

You may assume that the string has sufficient space at the end of the string to hold the additional characters.

And not:

You may assume that the string has exactly enough space at the end of the string to hold the additional characters.

Lesson 1 in code interviewing is to read (or listen to) the specification carefully. It's entirely possible that the array length is 1 million, but the string only contains two spaces. In this case, by assuming that you can just subtract the two lengths, you've assumed (without verifying) a part of the specification that wasn't explicit, and you'd almost certainly lose points for that.

|improve this answer|||||
  • Uhhh! That is SO true. I was assuming it ended with the exact amount of spaces needed to fill it out but it could be MORE because that still satisfies the condition of it having sufficient amount of spaces. Thank you so much! – AvetisG Feb 21 '15 at 19:12
1

the spaceCount loop counts all of the actual spaces in the string, and ignores the spaces at the end (since you've been given the actual length of the string minus the trailing space in the length parameter).

The spec doesn't say that the amount of space left at the end of the string coincides exactly with the required space to hold the additional characters, only that there is sufficient space.

|improve this answer|||||

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.