Skip to content
Work Practice Products Coding interviews Machine learning coding Quant developer HFT course Blog Method Why me About Enquire Book a call

Coding · Dynamic programming

The fewest insertions to make a palindrome

Hard · Target 20 minutes · Dynamic programming · Type asked atGoogleAmazon

Given a string s, return the fewest characters you must insert (anywhere) to make it a palindrome.

Examples

InputOutputWhy
s = "zzazz"0Already a palindrome.
s = "mbadm"2For example "mbdadbm".
s = "leetcode"5For example "leetcodocteel".

Constraints

  • 1 ≤ s.length ≤ 500
  • Lowercase English letters

Hints

Hint 1

ins(i, j) = fewest insertions for s[i..j]. Empty and single-character intervals need 0.

Hint 2

If s[i] = s[j]: ins(i + 1, j − 1). Otherwise insert a copy of one end: 1 + min(ins(i + 1, j), ins(i, j − 1)).

Hint 3

Equivalently: n − the longest palindromic subsequence.

Where people lose marks

  • Counting insertions at one end only.
  • Filling rows in increasing i, which reads row i + 1 before it is ready.
Console⌘/Ctrl + Enter runs

Write a solution and run it against the real test table.


Keep going

Preparing for a real process? Quant interview preparation, or book a free 20-minute call.