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 palindrome pattern

Lesson · 9 min read · Dynamic programming · Pattern: palindrome DP

Palindrome questions are interval questions: the ends of [i, j] must agree and the inside must already work.

The pattern

A palindrome is defined from the outside in: matching ends around a palindrome. So palindrome questions use the interval state [i, j], filled by increasing length, and the cell asks whether s[i] = s[j] and what the inside [i + 1, j − 1] gives. The earlier modules covered the longest subsequence and substring; the same table counts palindromic substrings and measures how far a string is from being a palindrome.

Palindrome DP

f(i, j)

  1. if s[i] = s[j]: build on f(i + 1, j − 1);
  2. otherwise combine f(i + 1, j) and f(i, j − 1).

order

  1. by increasing j − i.

Worked example: the fewest insertions to make a palindrome

ins(i, j) = ins(i + 1, j − 1) if the ends match, else 1 + min(ins(i + 1, j), ins(i, j − 1)).

For "aaab", by length.

  1. Step 1 / 11
    0a1a2a3b0a1a2a3b

    Base cases filled first.

  2. Step 2 / 11
    0a1a2a3b0a01a2a3b

    [0a, 0a] = 0.

  3. Step 3 / 11
    0a1a2a3b0a01a02a3b

    [1a, 1a] = 0.

  4. Step 4 / 11
    0a1a2a3b0a01a02a03b

    [2a, 2a] = 0.

  5. Step 5 / 11
    0a1a2a3b0a01a02a03b0

    [3b, 3b] = 0.

  6. Step 6 / 11
    0a1a2a3b0a001a02a03b0

    [0a, 1a] = 0.

  7. Step 7 / 11
    0a1a2a3b0a001a002a03b0

    [1a, 2a] = 0.

  8. Step 8 / 11
    0a1a2a3b0a001a002a013b0

    [2a, 3b] = 1.

  9. Step 9 / 11
    0a1a2a3b0a0001a002a013b0

    [0a, 2a] = 0.

  10. Step 10 / 11
    0a1a2a3b0a0001a0012a013b0

    [1a, 3b] = 1.

  11. Step 11 / 11
    0a1a2a3b0a00011a0012a013b0

    [0a, 3b] = 1. ins(0, 3) = 1: "aaab" needs one insertion ("baaab").

Problems