Skip to lesson

Palindrome dynamic programming solves substring and subsequence problems by expanding or collapsing inward from the ends. We start with brute-force checking to understand interval DP.

Brute Force Checking and Interval Subproblems

Palindrome: a string that reads the same forwards and backwards. Palindrome DP uses a table over index ranges [i, j] to record which substrings are palindromes.

A brute-force palindrome count checks every substring separately. There are O(n^2) possible substrings, and checking if each one is a palindrome takes O(n) time, leading to O(n^3) total time.

Java
int countPalindromes(String s) {    int count = 0;    for (int i = 0; i < s.length(); i++) {        for (int j = i; j < s.length(); j++) {      // O(n^2) substrings            int lo = i, hi = j;            while (lo < hi && s.charAt(lo) == s.charAt(hi)) { lo++; hi--; } // O(n)            if (lo >= hi) count++;        }    }    return count;}

Why is this wasteful? If 'racecar' is a palindrome, checking 'aracecara' only needs to verify that the outer letters match ('a' == 'a') and that the inner substring 'racecar' is already known to be a palindrome!

This is the core insight of interval DP: a substring s[i..j] is a palindrome if and only if s[i] == s[j] and the inner substring s[i + 1..j - 1] is also a palindrome.

Constructing the 2D Palindrome Table

Define dp[i][j] as a boolean: true if substring s[i..j] is a palindrome, false otherwise.

Base cases: all single characters (i == j) are palindromes (length 1). For two characters (length 2), s[i..i+1] is a palindrome if s[i] == s[i + 1].

Example 1 · Longest Palindromic Substring Length

LongestPalindromicSubstringDemo.javaJava
public class LongestPalindromicSubstringDemo {    public static int longestPalindromeLength(String s) {        int n = s.length();        if (n == 0) return 0;        boolean[][] dp = new boolean[n][n];        int maxLen = 1;        for (int i = 0; i < n; i++) dp[i][i] = true;        for (int i = 0; i < n - 1; i++) {            if (s.charAt(i) == s.charAt(i + 1)) {                dp[i][i + 1] = true;                maxLen = 2;            }        }        for (int len = 3; len <= n; len++) {            for (int i = 0; i <= n - len; i++) {                int j = i + len - 1;                if (s.charAt(i) == s.charAt(j) && dp[i + 1][j - 1]) {                    dp[i][j] = true;                    maxLen = len;                }            }        }        return maxLen;    }
    public static void main(String[] args) {        System.out.println("Max len in babad: " + longestPalindromeLength("babad"));        System.out.println("Max len in cbbd: " + longestPalindromeLength("cbbd"));    }}
Output
Max len in babad: 3
Max len in cbbd: 2

What this code does

  • Fills boolean table by increasing substring length from 1 to n.
  • Substring 'bab' or 'aba' has maximum length 3.
  • Substring 'bb' has maximum length 2 in 'cbbd'.

For lengths 3 and greater: dp[i][j] = (s[i] == s[j]) && dp[i + 1][j - 1]. Because length L depends on length L - 2, we iterate by substring length from 1 to n, filling the table in O(n^2) time and O(n^2) space.

Longest Palindromic Subsequence

Unlike substrings, subsequences do not need to be contiguous. Plain recursion compares ends: if s[i] == s[j], return 2 + lps(i + 1, j - 1). If mismatch, return Math.max(lps(i + 1, j), lps(i, j - 1)).

Example 2 · Longest Palindromic Subsequence

LongestPalindromicSubsequenceDemo.javaJava
public class LongestPalindromicSubsequenceDemo {    public static int longestPalindromeSubseq(String s) {        int n = s.length();        int[][] dp = new int[n][n];        for (int i = 0; i < n; i++) dp[i][i] = 1;        for (int len = 2; len <= n; len++) {            for (int i = 0; i <= n - len; i++) {                int j = i + len - 1;                if (s.charAt(i) == s.charAt(j)) {                    dp[i][j] = 2 + (len == 2 ? 0 : dp[i + 1][j - 1]);                } else {                    dp[i][j] = Math.max(dp[i + 1][j], dp[i][j - 1]);                }            }        }        return dp[0][n - 1];    }
    public static void main(String[] args) {        System.out.println("LPS in bbbab: " + longestPalindromeSubseq("bbbab"));        System.out.println("LPS in cbbd: " + longestPalindromeSubseq("cbbd"));    }}
Output
LPS in bbbab: 4
LPS in cbbd: 2

What this code does

  • In 'bbbab', subsequence 'bbbb' has maximum length 4.
  • In 'cbbd', subsequence 'bb' has maximum length 2.
  • Runs in O(n^2) time and O(n^2) auxiliary space.

Without memoization, mismatches branch twice at each step, running in exponential O(2^n) time. With dynamic programming, dp[i][j] stores the LPS length for range [i, j]. Filling by interval length takes O(n^2) time. Alternatively, LPS(s) equals LCS(s, reverse(s)).

Expand Around Center vs Dynamic Programming

Expand around center grows a palindrome outward from its middle while the two ends match. For palindromic substrings (counting or finding longest), it needs only O(1) extra space, while dynamic programming takes O(n^2) time and O(n^2) space.

Java
int expand(String s, int left, int right) {    int count = 0;    while (left >= 0 && right < s.length() && s.charAt(left) == s.charAt(right)) {        count++;          // s[left..right] is a palindrome        left--;        right++;    }    return count;}// total = sum of expand(s, i, i) + expand(s, i, i + 1) for every i

Notice that every palindrome expands outward from a center! There are 2n - 1 possible centers (n single characters and n - 1 adjacent pairs).

Expanding outward from each center until characters mismatch takes O(n^2) time and strictly O(1) extra space, avoiding the 2D table entirely when only substrings are needed.

Example 3 · Palindrome Partitioning Minimum Cuts

PalindromePartitionMinCutsDemo.javaJava
import java.util.Arrays;
public class PalindromePartitionMinCutsDemo {    public static int minCut(String s) {        int n = s.length();        boolean[][] isPal = new boolean[n][n];        for (int len = 1; len <= n; len++) {            for (int i = 0; i <= n - len; i++) {                int j = i + len - 1;                if (s.charAt(i) == s.charAt(j)) {                    isPal[i][j] = (len <= 2) || isPal[i + 1][j - 1];                }            }        }        int[] dp = new int[n];        for (int i = 0; i < n; i++) {            if (isPal[0][i]) {                dp[i] = 0;            } else {                int min = i;                for (int j = 1; j <= i; j++) {                    if (isPal[j][i]) {                        min = Math.min(min, dp[j - 1] + 1);                    }                }                dp[i] = min;            }        }        return dp[n - 1];    }
    public static void main(String[] args) {        System.out.println("Min cuts for aab: " + minCut("aab"));        System.out.println("Min cuts for a: " + minCut("a"));    }}
Output
Min cuts for aab: 1
Min cuts for a: 0

What this code does

  • Precomputes boolean palindrome table in O(n^2) time.
  • Partition 'aa' | 'b' requires exactly 1 cut for 'aab'.
  • Single character 'a' is already a palindrome requiring 0 cuts.

Next step

Check your understanding

10 quick questions