#214

Shortest Palindrome

Hard KMP on s + # + reverse

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

Add characters only to the front of s to make it a palindrome. Return the shortest such palindrome.

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: add the fewest letters in front to make a palindrome.

Why this works: find the longest palindromic prefix: run KMP on s + "#" + reverse(s). Whatever comes after it must be mirrored in front.

Example: "aacecaaa"

longest palindromic prefix "aacecaa" (7)leftover "a" → put "a" in front → "aaacecaaa"

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Leaving out the separator, so the LPS can be longer than s itself.

Solve on LeetCode ↗
Complexity
  • Time: O(n).
  • Space: O(n).
Topic: String Pattern Matching
🎬 Episodes 18–19: video coming soon