Add the least amount of characters to make a palindrome

Waley Chen picture Waley Chen · Sep 11, 2013 · Viewed 14.3k times · Source

The question:

Given any string, add the least amount of characters possible to make it a palindrome in linear time.

I'm only able to come up with a O(N2) solution.

Can someone help me with an O(N) solution?

Answer

Chronial picture Chronial · Sep 11, 2013
  1. Revert the string
  2. Use a modified Knuth-Morris-Pratt to find the latest match (simplest modification would be to just append the original string to the reverted string and ignore matches after len(string).
  3. Append the unmatched rest of the reverted string to the original.

1 and 3 are obviously linear and 2 is linear beacause Knuth-Morris-Pratt is.