Algorithms Efficiency – Most Efficient Way to Get Space Count in Strings

algorithmsefficiencystrings

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?

Best Answer

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.