How to remove blank spaces in a string with a complexity of O(n).
My approach is using two indexes. One will traverse till length on string. Other will be incremented only when a non-blank character is encountered.
But i am not sure of this approach.
TIA,
Praveen
This approach is fine. The O(n) requirement simply means that the running time is proportional to the number of items which in this case means the number of characters in the string (assuming you mean time complexity which is a fairly safe bet here).
The pseudocode:
is basically what you’re trying to do.
Because it has a single loop dependent only on the number of characters, it is indeed O(n) time complexity.
The following C program shows this in action:
Running this gives you:
Note that, if there are no spaces in the string, it simply copies every character over itself. You might think that you could optimise it by checking if
src == dstand not copying but you’ll probably find the check is as expensive as the copy. And, unless you’re frequently copying multi-megabyte strings, performance won’t be an issue here.Also keep in mind this will be undefined behaviour with
conststrings but that would be the case in any in-place modification.