Data Structures & AlgorithmsVery hardProduct Company SDE · ICPC regional

Problem: The shortest palindrome obtainable by inserting characters only at the front of "abacd" has what length?

  1. A. 9
  2. B. 7
  3. C. 10
  4. D. 2

Correct answer: B. 7

The longest palindromic prefix of 'abacd' is 'aba', so only 'dc' must be prepended: 'dcabacd' has length 7 (KMP on s + '#' + reverse(s) finds that prefix). Prepending everything but the first letter gives 2n − 1 = 9, prepending the whole reverse gives 10, and 2 counts inserted characters.

More Coding Interview Problems questions

Exams that ask this topic