Given a string, we need to check if a string is a double string possibly by deleting a character.
A double string is a repetition of two strings affixed together.
For example the following strings are double strings
"aa", "meme", "abbabb"
Where as the follwing are not double strings
"ab", "abc", "acbab"
"acbab" can be be a double string if we remove
"c" from it.
This problem was appeared in Codechef March 2016 long contest. Here is the link.
Let us try to analyze the problem. Consider the base case first. A string of length 0 or 1 can never be a double string. Hence, we have to consider the strings of length > 1. Also we can observe that a double string is always of even length.
If the given string is of even length, we simply need to check if it is a double string by checking if the left half and right half are equal.
No need to consider the case of deleting a character because, if we delete a character, it’s length will be odd which will never be a double string.
If the string is of odd length, we have to delete a character before checking if it is a double string. How to find out which character to be deleted?
Consider the following cases
"cabab", delete first character
"acbab", delete second character
"abcab", delete third character
"abacb", delete fourth character
"ababc", delete fifth character
So it appears that we should try to remove each possible character and check if it is a double string. However since we want to check for a double string,
the left and right half should atleast be similar if not equal.
Consider an example “acbab”, we can divide the string into longer and shorter halves in two ways
Since the first pair of string differ by only character (In other words, their edit distance is just 1)
So we just need to check if the edit distance between the longer and shorter strings is at most 1.
Here is the C++ implementation of the above algorithm. It runs in O(n) time.