Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 22

DP for Palindromic Subsequences

This lesson is built with resources from youtube.com and neetcode.io.

Introduction

Welcome to the next lesson in our dynamic programming module. In our previous session, we established a strong foundation in sequence comparison problems like Longest Common Subsequence (LCS) and Edit Distance. We saw how a 2D DP state, dp[i][j], can effectively solve problems involving prefixes of two strings.

This lesson builds directly on that foundation, focusing on a specific and common DP pattern involving palindromes. Our goal is to apply DP to string-based problems involving palindromes, with the classic example being Longest Palindromic Subsequence (LPS). As we'll see, one elegant way to solve this problem directly leverages the LCS algorithm we just learned, showcasing how different DP patterns can be connected. Mastering this topic is not just about solving a specific problem, but about demonstrating the ability to recognize underlying structures and apply known patterns—a key skill for a Staff-level role.


1. Defining the Problem: Subsequence vs. Substring

First, let's be precise. A palindrome is a sequence that reads the same forwards and backwards (e.g., "racecar").

We're interested in the longest palindromic subsequence. Remember from our last lesson, a subsequence is formed by deleting zero or more characters, while maintaining the relative order of the remaining characters. This is distinct from a substring, which must be a contiguous block of characters.

  • For the string "bbbab", the longest palindromic substring is "bbb".
  • For the same string "bbbab", the longest palindromic subsequence is "bbbb" (by picking the four 'b's).

The following image provides another clear example.

Longest Palindromic Subsequence Example
For the string "BANANA", various palindromic subsequences exist. The longest among them is "ANANA", which has a length of 5.

Our task is to write an algorithm that, given a string s, finds the length of its longest palindromic subsequence.


2. Approach 1: The Longest Common Subsequence Reduction

Let's start with a clever insight that connects this problem directly to our previous lesson.

What is the relationship between a string s and a palindrome? A palindrome is a string that equals its own reverse.

Consider a string s and its reverse, s_rev. Any palindromic subsequence of s must, by definition, appear in s in the correct forward order. Crucially, it must also appear in s_rev in the same order, because reading the palindrome backwards (which is what you're doing when you read s_rev) gives you the same sequence.

This leads to a powerful conclusion:
The Longest Palindromic Subsequence of s is equivalent to the Longest Common Subsequence of s and s_rev.

This reduces the LPS problem to the LCS problem, which you already know how to solve!

Longest Palindromic Subsequence - Leetcode 516 - Python

The video from NeetCodeIO explains this reduction very clearly and provides a proof of why this approach is guaranteed to work.

Watch the first 4 minutes and 41 seconds of this video (00:00 - 04:41). Focus on understanding the core argument: why finding the LCS of a string and its reverse correctly yields the LPS.

Implementation in Go

Since you know how to implement LCS, this approach becomes straightforward. You simply need to reverse the input string and pass both the original and reversed versions to your LCS function.

516. Longest Palindromic Subsequence - Explanation

The NeetCode solutions page for this problem includes an implementation based on this LCS idea. It's a great example of reusing a known pattern.

Please read section '3. Dynamic Programming (Using LCS Idea)'. Pay attention to the Go code, which shows how a longestCommonSubsequence function is called with the string and its reverse to get the final answer. This is a very clean and concise solution.

While elegant, an interviewer might ask you to solve this problem without relying on an existing LCS function. This forces you to reason about the palindrome property directly, which we'll do next.


3. Approach 2: Direct Dynamic Programming

Let's build a DP solution from first principles. For this type of problem, where we're looking for a property within a range of a sequence, a good DP state definition is often dp[i][j], representing the solution for the substring from index i to j.

Let dp[i][j] be the length of the longest palindromic subsequence within the substring s[i...j].

Our goal is to find dp[0][n-1], where n is the length of the string.

The Recurrence Relation

To compute dp[i][j], we look at the characters at the boundaries of our substring: s[i] and s[j].

  1. If s[i] == s[j]:
    The characters at the ends match! This means they can form the outer shell of a palindrome. We get to add 2 to our length, and the rest of the problem is to find the LPS of the inner substring s[i+1...j-1].

  2. If s[i] != s[j]:
    The end characters don't match, so they can't both be part of the same palindrome. We have to make a choice:

    • Either we discard s[i] and find the LPS of s[i+1...j].
    • Or we discard s[j] and find the LPS of s[i...j-1].
      We want the longest subsequence, so we take the maximum of these two possibilities.

Base Cases

  • If i == j, the substring has one character. This is a palindrome of length 1. So, dp[i][i] = 1.
  • If i > j, we have an empty substring. The LPS length is 0. This is useful for the recursive calls, e.g., when s[i] == s[j] and j = i + 1, the inner subproblem becomes dp[i+1][i], which should evaluate to 0.

DP - 9: Longest Palindrome Subsequence

This video from Coding Simplified provides a detailed explanation of this direct DP approach, starting with the recursive logic and then moving to both top-down and bottom-up implementations.

Please watch from 02:20 to 07:13, and then from 12:58 to 14:49. The first segment explains the recursive logic and base cases. The second segment analyzes the overlapping subproblems and optimal substructure, justifying why DP is applicable.


4. Implementation and Complexity

Now let's translate this logic into code. A top-down approach with memoization is a very natural way to implement this recurrence.

Top-Down (Memoization) in Go

516. Longest Palindromic Subsequence - Explanation

The NeetCode page provides an excellent 'Top-Down Optimized' implementation that directly follows the recurrence we just defined. It's clean, idiomatic Go and serves as a great interview template.

Read section '2. Dynamic Programming (Top-Down Optimized)'. Study the Go code carefully. Notice how the dfs(i, j) function implements the base cases (i > j, i == j) and the two recursive steps we discussed.

  • Time Complexity: The number of states is i * j, which is approximately N * N. Since each state is computed once thanks to memoization, the time complexity is .
  • Space Complexity: The memoization table dp requires space. The recursion stack depth is at most N, so the total space is .

Bottom-Up (Tabulation)

For a bottom-up approach, we need to fill the dp table such that dp[i+1][j-1], dp[i+1][j], and dp[i][j-1] are already computed before we compute dp[i][j]. This means we need to calculate results for smaller substrings before larger ones.

We can achieve this by iterating through substring lengths, or more commonly, by iterating i from n-1 down to 0 and j from i+1 up to n-1.

DP - 9: Longest Palindrome Subsequence

Let's revisit the Coding Simplified video to see how this bottom-up table is filled.

Watch from 19:11 to 29:55. This section provides a detailed walk-through of filling the 2D DP table. Pay special attention to the loop structure (i going backwards, j going forwards) as this is a key pattern for interval-based DP problems.


5. Space Optimization (Staff+ Detail)

In an interview, especially for a senior role, a follow-up question might be: "Can you optimize the space complexity?"

For the bottom-up approach, notice that to compute a row i, you only need values from row i+1. This is similar to the LCS and Knapsack problems we've seen. However, the dependency on dp[i+1][j-1] (the diagonal element) makes the standard row-by-row optimization tricky.

A more direct way to optimize space for this particular loop structure is to realize that when calculating dp[j] for the current row i, we need dp[j] (from row i+1), dp[j-1] (from the current row i), and a value from the i+1 row at column j-1.

The following resource shows how to achieve space with a clever use of a temporary variable to save the "top-left" value before it's overwritten.

516. Longest Palindromic Subsequence - Explanation

This is a great optimization to have in your toolkit. It shows a deeper level of thinking about DP state transitions.

Read section '4. Dynamic Programming (Space Optimized)'. The logic can be subtle, so trace the Go code with a small example like s = "bbbab". Understand how the prev variable is used to store the value of dp[j] from the previous outer loop iteration, which effectively corresponds to dp[i+1][j-1].


Conclusion

In this lesson, we explored how to solve palindrome problems using dynamic programming, focusing on the Longest Palindromic Subsequence.

Key Takeaways:

  • Problem Recognition: LPS can be solved in two ways: by a clever reduction to Longest Common Subsequence (LCS) or by building a direct DP solution. Knowing both demonstrates flexibility.
  • Direct DP Recurrence: The state dp[i][j] represents the LPS of the substring s[i...j]. The recurrence depends on whether s[i] and s[j] match, leading to a decision between including both end characters or taking the best of two smaller subproblems.
  • Bottom-Up Iteration: The bottom-up solution requires a specific iteration order (e.g., i backwards, j forwards) to ensure subproblems are solved before they are needed. This is a hallmark of "interval DP".
  • Complexity and Optimization: The standard solution has time and space complexity. For Staff-level interviews, being able to discuss and implement the space optimization is a significant plus.

Preview of the Next Lesson:
The direct DP approach we learned for LPS is a form of Interval DP, where the solution for an interval [i, j] is built from solutions for smaller, nested intervals. In our next lesson, we will formalize this pattern and apply it to more complex problems like Burst Balloons and Matrix Chain Multiplication, where the decision process involves choosing a "split point" within the interval.