I was recently in a C++ technical interview, where I was given a bit of simple string manipulation code, which is intended to take a string and return a string that is comprised
If you don't need to maintain the contents of the original string, then you can copy the last n characters into positions [n+1, 2n]
of the original string and truncate it at 2n
. You will have to be careful to first expand the string and also be careful not to overwrite any characters before writing to them if the string is shorter than 2n
.
This will halve the number of operations to construct the string, as well as remove the need to create a new string. So its theoretically between 2 and 4 times faster. But of course you have just destroyed the original string, which you'd have to ask the interviewer if it is acceptable.