cswork / templatesOpen the Line 500 list

STOP 27 · DYNAMIC PROGRAMMING

Palindromes and Interval States

Interval DP with the left end running backwards O(n²)

Contest ratings Rating 1787–Rating 2130· median Rating 1959(2 of 7 problems rated by zerotrac)

Open the Line 500 list · stop 27 · 7 problems
Learn first
Leads to
No later stop builds on it.
How often asked
asked by 5 companies · in 5 reportsInterSystems 1, JPMorgan Chase 1, Meta 1, Reevo 1, TikTok / ByteDance 1

Warm up with this one

LC 5Longest Palindromic SubstringMedium
Stuck? Peek at the approach

Compare center expansion with interval DP, handling odd and even centers and returning the longest slice of the original string.

Key points

  1. dp[i][j] depends only on shorter ranges, dp[i+1][*] and dp[*][j-1], so fill i backwards and j forwards.
  2. If the two ends match, shrink inward and add 2; otherwise drop one end and keep the better of the two.
  3. For palindromic substrings (contiguous), expanding around each center is simpler: O(n²) time and O(1) space.

Common pitfalls

  • Iterating i forwards reads dp[i+1][*] before it has been computed.
  • Subsequence (gaps allowed) and substring (contiguous) are different problems with different transitions.
  • Center expansion must try both odd centers (i, i) and even centers (i, i+1).

Watch it run

Step through the pattern on a small example. Pause, step forwards or back, or drag the slider to any step.

Interactive demo · step by step

Interval DP · longest palindromic subsequence

How long is the longest palindromic subsequence of "agbdba"?

Try your own input
a0
g1
b2
d3
b4
a5
a0
·0,0
·0,1
·0,2
·0,3
·0,4
·0,5
g1
·1,1
·1,2
·1,3
·1,4
·1,5
b2
·2,2
·2,3
·2,4
·2,5
d3
·3,3
·3,4
·3,5
b4
·4,4
·4,5
a5
·5,5
CurrentDiscovered / computedAnswer
Interval length
—
Longest palindromic subsequence
—

dp[i][j] is the longest palindromic subsequence within characters i..j of "agbdba". It depends on shorter intervals, so fill by interval length, short to long.

InvariantWhen an interval of length L is filled, every shorter one is final: equal ends add 2, unequal ends drop one side.

Template

Open one language. All four implement the same template, and each one is compiled, run and checked against test data. Then rewrite the warm-up, LC 5, with it.

Python
def longest_pal_subseq(s: str) -> int:
    n = len(s)
    dp = [[0] * n for _ in range(n)]  # dp[i][j]: answer for s[i..j]
    for i in range(n - 1, -1, -1):  # i backwards so dp[i+1][*] is ready
        dp[i][i] = 1
        for j in range(i + 1, n):
            if s[i] == s[j]:
                dp[i][j] = dp[i + 1][j - 1] + 2
            else:
                dp[i][j] = max(dp[i + 1][j], dp[i][j - 1])
    return dp[0][n - 1] if n else 0
C++
int longestPalSubseq(const string& s) {
    int n = s.size();
    if (n == 0) return 0;
    vector<vector<int>> dp(n, vector<int>(n, 0));  // dp[i][j]: answer for s[i..j]
    for (int i = n - 1; i >= 0; i--) {  // i backwards so dp[i+1][*] is ready
        dp[i][i] = 1;
        for (int j = i + 1; j < n; j++)
            dp[i][j] = s[i] == s[j] ? dp[i + 1][j - 1] + 2 : max(dp[i + 1][j], dp[i][j - 1]);
    }
    return dp[0][n - 1];
}
Java
class Solution {
    int longestPalSubseq(String s) {
        int n = s.length();
        if (n == 0) return 0;
        int[][] dp = new int[n][n]; // dp[i][j]: answer for s[i..j]
        for (int i = n - 1; i >= 0; i--) { // i backwards so dp[i+1][*] is ready
            dp[i][i] = 1;
            for (int j = i + 1; j < n; j++)
                dp[i][j] = s.charAt(i) == s.charAt(j)
                        ? dp[i + 1][j - 1] + 2
                        : Math.max(dp[i + 1][j], dp[i][j - 1]);
        }
        return dp[0][n - 1];
    }
}
Go
func longestPalSubseq(s string) int {
	n := len(s)
	if n == 0 {
		return 0
	}
	dp := make([][]int, n) // dp[i][j]: answer for s[i..j]
	for i := range dp {
		dp[i] = make([]int, n)
	}
	for i := n - 1; i >= 0; i-- { // i backwards so dp[i+1][*] is ready
		dp[i][i] = 1
		for j := i + 1; j < n; j++ {
			if s[i] == s[j] {
				dp[i][j] = dp[i+1][j-1] + 2
			} else {
				dp[i][j] = max(dp[i+1][j], dp[i][j-1])
			}
		}
	}
	return dp[0][n-1]
}

Common variants

Problems at this stop also need the 2 shapes below. Open one to see when to switch to it; its code is tested in all four languages too.

Expand around centres: 2n − 1 of themO(n²) time · O(1) space

When only palindromic substrings (contiguous) matter, no n² table is needed: treat every letter and every gap between letters as a centre and expand while both sides match, O(n²) time and O(1) space. LC 5 (Longest Palindromic Substring) and LC 647 (Palindromic Substrings) are written this way; subsequences (non-contiguous) are what need interval DP.

Python
def longest_palindrome(s: str) -> str:
    """Longest palindromic substring, expanding around all 2n - 1 centres (LC 5)."""
    start = end = 0  # the best so far is s[start:end]
    for center in range(2 * len(s) - 1):
        lo, hi = center // 2, (center + 1) // 2  # even centre: a letter; odd: the gap after it
        while lo >= 0 and hi < len(s) and s[lo] == s[hi]:
            lo, hi = lo - 1, hi + 1
        if hi - lo - 1 > end - start:  # the palindrome found is s[lo+1:hi]
            start, end = lo + 1, hi
    return s[start:end]
C++
// Longest palindromic substring, expanding around all 2n - 1 centres (LC 5).
string longestPalindrome(const string& s) {
    int n = s.size(), start = 0, end = 0;  // the best so far is s[start, end)
    for (int center = 0; center < 2 * n - 1; center++) {
        int lo = center / 2, hi = (center + 1) / 2;  // even centre: a letter; odd: the gap after it
        while (lo >= 0 && hi < n && s[lo] == s[hi]) lo--, hi++;
        if (hi - lo - 1 > end - start) start = lo + 1, end = hi;  // the palindrome found is s[lo+1, hi)
    }
    return s.substr(start, end - start);
}
Java
class Solution {
    // Longest palindromic substring, expanding around all 2n - 1 centres (LC 5).
    String longestPalindrome(String s) {
        int n = s.length(), start = 0, end = 0; // the best so far is s[start, end)
        for (int center = 0; center < 2 * n - 1; center++) {
            int lo = center / 2, hi = (center + 1) / 2; // even centre: a letter; odd: the gap after it
            while (lo >= 0 && hi < n && s.charAt(lo) == s.charAt(hi)) {
                lo--;
                hi++;
            }
            if (hi - lo - 1 > end - start) { // the palindrome found is s[lo+1, hi)
                start = lo + 1;
                end = hi;
            }
        }
        return s.substring(start, end);
    }
}
Go
// longestPalindrome returns the longest palindromic substring, expanding around all 2n - 1 centres (LC 5).
func longestPalindrome(s string) string {
	n, start, end := len(s), 0, 0 // the best so far is s[start:end]
	for center := 0; center < 2*n-1; center++ {
		lo, hi := center/2, (center+1)/2 // even centre: a letter; odd: the gap after it
		for lo >= 0 && hi < n && s[lo] == s[hi] {
			lo, hi = lo-1, hi+1
		}
		if hi-lo-1 > end-start { // the palindrome found is s[lo+1:hi]
			start, end = lo+1, hi
		}
	}
	return s[start:end]
}
Interval DP: choose the last element handled in the rangeO(n³) time · O(n²) space

When an operation changes the neighbours (bursting a balloon closes the gap, merging stones), enumerating the first move gets stuck; enumerate the last one instead. When k goes last, its neighbours are exactly the range ends i and j, and the two sides no longer interact. Run i backwards and j forwards so smaller ranges are ready. LC 312 (Burst Balloons), LC 1039 (Minimum Score Triangulation of Polygon).

Python
def max_coins(nums: list[int]) -> int:
    """Most coins from bursting all balloons (LC 312): pick the last one burst in each range."""
    vals = [1] + nums + [1]
    n = len(vals)
    dp = [[0] * n for _ in range(n)]  # dp[i][j]: best for the balloons strictly between i and j
    for i in range(n - 1, -1, -1):  # i backwards so dp[k][j] with k > i is ready
        for j in range(i + 2, n):
            for k in range(i + 1, j):  # k goes last: its neighbours are then i and j
                dp[i][j] = max(dp[i][j], dp[i][k] + dp[k][j] + vals[i] * vals[k] * vals[j])
    return dp[0][n - 1]
C++
// Most coins from bursting all balloons (LC 312): pick the last one burst in each range.
int maxCoins(const vector<int>& nums) {
    vector<int> vals{1};
    vals.insert(vals.end(), nums.begin(), nums.end());
    vals.push_back(1);
    int n = vals.size();
    vector<vector<int>> dp(n, vector<int>(n, 0));  // dp[i][j]: best for the balloons strictly between i and j
    for (int i = n - 1; i >= 0; i--)  // i backwards so dp[k][j] with k > i is ready
        for (int j = i + 2; j < n; j++)
            for (int k = i + 1; k < j; k++)  // k goes last: its neighbours are then i and j
                dp[i][j] = max(dp[i][j], dp[i][k] + dp[k][j] + vals[i] * vals[k] * vals[j]);
    return dp[0][n - 1];
}
Java
class Solution {
    // Most coins from bursting all balloons (LC 312): pick the last one burst in each range.
    int maxCoins(int[] nums) {
        int n = nums.length + 2;
        int[] vals = new int[n];
        vals[0] = vals[n - 1] = 1;
        System.arraycopy(nums, 0, vals, 1, nums.length);
        int[][] dp = new int[n][n]; // dp[i][j]: best for the balloons strictly between i and j
        for (int i = n - 1; i >= 0; i--) // i backwards so dp[k][j] with k > i is ready
            for (int j = i + 2; j < n; j++)
                for (int k = i + 1; k < j; k++) // k goes last: its neighbours are then i and j
                    dp[i][j] = Math.max(dp[i][j], dp[i][k] + dp[k][j] + vals[i] * vals[k] * vals[j]);
        return dp[0][n - 1];
    }
}
Go
// maxCoins returns the most coins from bursting all balloons (LC 312).
func maxCoins(nums []int) int {
	vals := append(append([]int{1}, nums...), 1)
	n := len(vals)
	dp := make([][]int, n) // dp[i][j]: best for the balloons strictly between i and j
	for i := range dp {
		dp[i] = make([]int, n)
	}
	for i := n - 1; i >= 0; i-- { // i backwards so dp[k][j] with k > i is ready
		for j := i + 2; j < n; j++ {
			for k := i + 1; k < j; k++ { // k goes last: its neighbours are then i and j
				dp[i][j] = max(dp[i][j], dp[i][k]+dp[k][j]+vals[i]*vals[k]*vals[j])
			}
		}
	}
	return dp[0][n-1]
}

Why it works

  1. dp[i][j], the longest palindromic subsequence of s[i..j], depends only on dp[i+1][j−1], dp[i+1][j] and dp[i][j−1], all shorter ranges, so filling i backwards and j forwards guarantees they are ready.
  2. When the ends match, using both is never worse: an optimal palindrome that does not use both can swap its outermost pair for them without getting shorter.
  3. Expanding around centres: every palindromic substring has a unique centre, a character or the gap between two, so expanding from all 2n − 1 centres enumerates every palindromic substring.

Say it in 30 seconds

When the interviewer asks you to talk it through: the approach, why it is correct, then the cost. One version in each language to read aloud a few times.

中文
回文区间 DP,我定义 dp[i][j] 为 s[i..j] 上的答案。两端相等就向内收缩并加 2,否则去掉一端,在两种里取更好的。每个状态只依赖更短的区间,所以 i 从后往前、j 从前往后填表。如果是连续的回文子串,我更常用中心扩展:2n − 1 个中心各自向外扩,O(n²) 时间、O(1) 空间。
English
For palindrome ranges I let dp[i][j] be the answer on s[i..j]. If the two ends match, I move inward and add two; otherwise I drop one end and keep the better result. Every state depends only on shorter ranges, so I fill i backwards and j forwards. For contiguous palindromic substrings I usually expand around each of the 2n − 1 centres instead, which is O(n²) time and O(1) space.

Grade yourself

Grade your answer against the one above. Questions you have not mastered come back after 1, 3, 7 and 21 days, listed under My progress → Due for review. Kept on this device; sign in and it moves to your account.

Key points you covered (0 of 3)
How well did you know it?

Quick quiz

4 concept and complexity questions. Answered ones come back for spaced review along with the OA multiple-choice practice. Open the OA multiple-choice practice

4 questions
  1. Expand-around-center for palindromic substrings: how many centers does a string of length n have?
  2. Longest palindromic subsequence: dp[i][j] needs dp[i+1][j-1], dp[i+1][j] and dp[i][j-1]. Which fill order works?
  3. n = len(s). What are the worst-case time and extra space?
    def count_pal(s):
        n, total = len(s), 0
        for c in range(2 * n - 1):
            lo, hi = c // 2, c // 2 + c % 2
            while lo >= 0 and hi < n and s[lo] == s[hi]:
                total += 1
                lo -= 1
                hi += 1
        return total
  4. n = len(s). What is the time complexity?
    def count_pal(s):
        n = len(s)
        return sum(s[i:j] == s[i:j][::-1]
                   for i in range(n) for j in range(i + 1, n + 1))

Your answers stay in this browser on this device; open OA multiple-choice practice signed in to keep them in your account.

Template drills

Drills cut from the templates above: put shuffled lines back in order, fill the blanked boundary conditions back in, or write a whole template from memory in an empty editor, run against this stop's tests and compared line by line. Another one gives a new drill.

These lines are shuffled. Tap a line to pick it, then tap another to swap them, until they read as the template does; the indentation is a hint.

Practice by stage

This stop's 7 Line 500 problems in three stages: Foundation, Core and Advanced. Each has a one-line approach; try it yourself before reading it.

Core 4

#ProblemApproachRating
5Longest Palindromic SubstringCompare center expansion with interval DP, handling odd and even centers and returning the longest slice of the original string.
647Palindromic SubstringsCount palindromes by enumerating centers, distinguishing occurrences by position rather than deduplicating their text.
516Longest Palindromic SubsequenceDistinguish substrings from subsequences and optimize length through matching or skipping the two endpoints.
1312Minimum Insertion Steps to Make a String PalindromeResolve mismatched endpoints with one insertion and connect the recurrence to the longest palindromic subsequence.Rating 1787

Advanced 3

#ProblemApproachRating
132Palindrome Partitioning IIPrecompute palindromic intervals before minimizing cuts, distinguishing cut count from the number of segments.
1039Minimum Score Triangulation of PolygonFix a polygon edge and enumerate the third vertex to split into independent intervals, providing an intuitive interval-partitioning model.Rating 2130
312Burst BalloonsChoose the last balloon to burst so neighboring boundaries stay fixed, practicing reverse reasoning about operation order.