I don't know whether there is a O(N)
solution but by comparing with the reverse, you find a subsequence which is a palindrome. Then you have l-x
letters that are not paired. (You can consider a letter's pair as its reflection if you have a mirror right at the middle of the word. e.g. ab|ba) Later, by insertions you just complete the picture.
Now,firstly, how do we find a (maximum)subsequence that is common to two strings? There is a polynomial algorithm for finding it see it here
https://en.wikipedia.org/wiki/Longest_common_subsequence_problem
When we try to find the longest common subsequence(lcs) between s1 and s2(reverse of s1) we actually find lcs between the first half of s1 and first half s2, also second half of s1 and second half of s2.
Assume
s1 = abcddzac
so s2 = cazddcba
. Here we can see it as comparison of abcd
with cazd
(first half) plus comparison of dzac
with dcba
(second half). We can see that both of comparisons are the same except they are reverse of each other so their concatenation has to be palindrome, so lcs of s1 and s2 has to be palindrome.
Once we have the lcs(ad|da
) which is of length 4, we have 4 more letters that break the symmetry(b,c,z,c). Then we insert one letter for each of them to make a symmetry, i.e. a palindrome. We set our middle point as the middle point of the lcs and consider that we break s1 into two from that middle point so we have
s1 = a
bc d|d
z a
c and we break it like a stick into two from d|d and we end up with:
d
za
c
d
cba
now we simply fill between the letters of lcs so that they are the same. In our case steps are as follows:
d
za
c
d
cba
d
za
c
d
zcba
d
zca
c
d
zcba
d
zcba
c
d
zcba
d
zcba
c
d
zcba
c
Now we unbreak it from the same point and we have
ca
bczdd
zcba
c which is a palindrome.
Note: cddc is also an ldc but that doesn't change the number of steps.