CMD Guide
HomeDSACompany Practice

medium Longest Palindromic Subsequence

Problem Statement

Given a sequence, find the length of its Longest Palindromic Subsequence (LPS). In a palindromic subsequence, elements read the same backward and forward.

A subsequence is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements.

Example 1:

Input: "abdbca"
Output: 5
Explanation: LPS is "abdba".

Example 2:

Input: = "cddpd"
Output: 3
Explanation: LPS is "ddd".

Example 3:

Input: = "pqr"
Output: 1
Explanation: LPS could be "p", "q" or "r".

Constraints:

Try it yourself

Try solving this question here:

🎯 STRICT STANDOUT — Longest Palindromic Subsequence — problem

0. Pattern family

Family: DP / LPS ≡ LCS(s, reverse(s))

1. Why / judgment (K3)

Recognition before coding: subsequence (not substring) that is palindrome → classic interval DP or reduce to LCS of s and reverse(s). Interviewer probes state definition first: dp[i][j] = LPS length in s[i..j].

2. Worked complexity / derivation (K11)

Target algos: O(n²) DP time, O(n²) or O(n) space after rolling.
Brute subsequences 2^n — fail n≤1000. LCS on s and rev(s): O(n²).
Interval DP same O(n²).

3. Pattern + recognition + when-NOT (K12)

Name: LPS INTERVAL DP / LCS-WITH-REVERSE

Recognition: longest palindrome as subsequence; n up to ~1000 → O(n²) expected.

When-NOT: Longest palindromic substring → expand centers O(n²) different state. Subsequence vs substring trap.

4. Edge hand-run (K13)

s="bbbab" → 4 (bbbb). s="cbbd" → 2. s="a" → 1. s="ac" → 1.

5. Interviewer follow-ups & drills

Q1. State in words?
Model answer: dp[i][j] longest palindromic subsequence in inclusive range i..j.

Q2. Transition?
Model answer: if s[i]==s[j]: 2+dp[i+1][j−1] else max(dp[i+1][j], dp[i][j−1]).

Q3. Substring version?
Model answer: contiguous → expand-around-center or DP on length, not free skips.

✅ Solution Longest Palindromic Subsequence

Problem Statement

Given a sequence, find the length of its Longest Palindromic Subsequence (LPS). In a palindromic subsequence, elements read the same backward and forward.

A subsequence is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements.

Example 1:

Input: "abdbca"
Output: 5
Explanation: LPS is "abdba".

Example 2:

Input: = "cddpd"
Output: 3
Explanation: LPS is "ddd".

Example 3:

Input: = "pqr"
Output: 1
Explanation: LPS could be "p", "q" or "r".

Constraints:

  • 1 <= st.length <= 1000
  • sy consists only of lowercase English letters.

Basic Solution

A basic brute-force solution could be to try all the subsequences of the given sequence. We can start processing from the beginning and the end of the sequence. So at any step, we have two options:

  1. If the element at the beginning and the end are the same, we increment our count by two and make a recursive call for the remaining sequence.
  2. We will skip the element either from the beginning or the end to make two recursive calls for the remaining subsequence.

If option one applies then it will give us the length of LPS; otherwise, the length of LPS will be the maximum number returned by the two recurse calls from the second option.

Code

Here is the code:

java
class Solution {

  public int findLPSLength(String st) {
    return findLPSLengthRecursive(st, 0, st.length() - 1);
  }

  private int findLPSLengthRecursive(String st, int startIndex, int endIndex) {
    if (startIndex > endIndex) return 0;

    // every sequence with one element is a palindrome of length 1
    if (startIndex == endIndex) return 1;

    // case 1: elements at the beginning and the end are the same
    if (st.charAt(startIndex) == st.charAt(endIndex)) return (
      2 + findLPSLengthRecursive(st, startIndex + 1, endIndex - 1)
    );

    // case 2: skip one element either from the beginning or the end
    int c1 = findLPSLengthRecursive(st, startIndex + 1, endIndex);
    int c2 = findLPSLengthRecursive(st, startIndex, endIndex - 1);
    return Math.max(c1, c2);
  }

  public static void main(String[] args) {
    Solution lps = new Solution();
    System.out.println(lps.findLPSLength("abdbca"));
    System.out.println(lps.findLPSLength("cddpd"));
    System.out.println(lps.findLPSLength("pqr"));
  }
}

In each function call, we are either having one recursive call or two recursive calls (we will never have three recursive calls); hence, the time complexity of the above algorithm is exponential , where 'n' is the length of the input sequence. The space complexity is , which is used to store the recursion stack.

Top-down Dynamic Programming with Memoization

We can use an array to store the already solved subproblems.

The two changing values to our recursive function are the two indexes, startIndex and endIndex. Therefore, we can store the results of all the subproblems in a two-dimensional array. (Another alternative could be to use a hash-table whose key would be a string (startIndex + "|" + endIndex))

Code

Here is the code for this:

java
class Solution {

  public int findLPSLength(String st) {
    Integer[][] dp = new Integer[st.length()][st.length()];
    return findLPSLengthRecursive(dp, st, 0, st.length() - 1);
  }

  private int findLPSLengthRecursive(
    Integer[][] dp,
    String st,
    int startIndex,
    int endIndex
  ) {
    if (startIndex > endIndex) return 0;

    // every sequence with one element is a palindrome of length 1
    if (startIndex == endIndex) return 1;

    if (dp[startIndex][endIndex] == null) {
      // case 1: elements at the beginning and the end are the same
      if (st.charAt(startIndex) == st.charAt(endIndex)) {
        dp[startIndex][endIndex] =
          2 + findLPSLengthRecursive(dp, st, startIndex + 1, endIndex - 1);
      } else {
        // case 2: skip one element either from the beginning or the end
        int c1 = findLPSLengthRecursive(dp, st, startIndex + 1, endIndex);
        int c2 = findLPSLengthRecursive(dp, st, startIndex, endIndex - 1);
        dp[startIndex][endIndex] = Math.max(c1, c2);
      }
    }

    return dp[startIndex][endIndex];
  }

  public static void main(String[] args) {
    Solution lps = new Solution();
    System.out.println(lps.findLPSLength("abdbca"));
    System.out.println(lps.findLPSLength("cddpd"));
    System.out.println(lps.findLPSLength("pqr"));
  }
}

What is the time and space complexity of the above solution? Since our memoization array dp[st.length()][st.length()] stores the results for all the subproblems, we can conclude that we will not have more than subproblems (where 'N' is the length of the input sequence). This means that our time complexity will be .

The above algorithm will be using space for the memoization array. Other than that we will use space for the recursion call-stack. So the total space complexity will be , which is asymptotically equivalent to .

Bottom-up Dynamic Programming

Since we want to try all the subsequences of the given sequence, we can use a two-dimensional array to store our results. We can start from the beginning of the sequence and keep adding one element at a time. At every step, we will try all of its subsequences. So for every startIndex and endIndex in the given string, we will choose one of the following two options:

  1. If the element at the startIndex matches the element at the endIndex, the length of LPS would be two plus the length of LPS till startIndex+1 and endIndex-1.
  2. If the element at the startIndex does not match the element at the endIndex, we will take the maximum LPS created by either skipping element at the startIndex or the endIndex.

So our recursive formula would be:

if st[endIndex] == st[startIndex] dp[startIndex][endIndex] = 2 + dp[startIndex + 1][endIndex - 1] else dp[startIndex][endIndex] = Math.max(dp[startIndex + 1][endIndex], dp[startIndex][endIndex - 1])

Let's draw this visually for "cddpd", starting with a subsequence of length '1'. As we know, every sequence with one element is a palindrome of length 1:

Every sequence with one element is a palindrome of length 1
Every sequence with one element is a palindrome of length 1
startIndex:3, endIndex:4 => st[startIndex] !=st[endIndex], so dp[startIndex][endIndex] = max(dp[startIndex + 1][endIndex], dp[startIndex][endIndex - 1])
startIndex:3, endIndex:4 => st[startIndex] !=st[endIndex], so dp[startIndex][endIndex] = max(dp[startIndex + 1][endIndex], dp[startIndex][endIndex - 1])
startIndex:2, endIndex:3 => st[startIndex] !=st[endIndex], so dp[startIndex][endIndex] = max(dp[startIndex + 1][endIndex], dp[startIndex][endIndex - 1])
startIndex:2, endIndex:3 => st[startIndex] !=st[endIndex], so dp[startIndex][endIndex] = max(dp[startIndex + 1][endIndex], dp[startIndex][endIndex - 1])
startIndex:2, endIndex:4 => st[startIndex] ==st[endIndex], so dp[startIndex][endIndex] = 2 + dp[startIndex + 1][endIndex - 1]
startIndex:2, endIndex:4 => st[startIndex] ==st[endIndex], so dp[startIndex][endIndex] = 2 + dp[startIndex + 1][endIndex - 1]
startIndex:1, endIndex:2 => st[startIndex] ==st[endIndex], so dp[startIndex][endIndex] = 2 + dp[startIndex + 1][endIndex - 1]
startIndex:1, endIndex:2 => st[startIndex] ==st[endIndex], so dp[startIndex][endIndex] = 2 + dp[startIndex + 1][endIndex - 1]
startIndex:1, endIndex:3 => st[startIndex] !=st[endIndex], so dp[startIndex][endIndex] = max(dp[startIndex + 1][endIndex], dp[startIndex][endIndex - 1])
startIndex:1, endIndex:3 => st[startIndex] !=st[endIndex], so dp[startIndex][endIndex] = max(dp[startIndex + 1][endIndex], dp[startIndex][endIndex - 1])
startIndex:1, endIndex:4 => st[startIndex] ==st[endIndex], so dp[startIndex][endIndex] = 2 + dp[startIndex + 1][endIndex - 1]
startIndex:1, endIndex:4 => st[startIndex] ==st[endIndex], so dp[startIndex][endIndex] = 2 + dp[startIndex + 1][endIndex - 1]
startIndex:0, endIndex:1 => st[startIndex] !=st[endIndex], so dp[startIndex][endIndex] = max(dp[startIndex + 1][endIndex], dp[startIndex][endIndex - 1])
startIndex:0, endIndex:1 => st[startIndex] !=st[endIndex], so dp[startIndex][endIndex] = max(dp[startIndex + 1][endIndex], dp[startIndex][endIndex - 1])
startIndex:0, endIndex:4 => st[startIndex] !=st[endIndex], so dp[startIndex][endIndex] = max(dp[startIndex + 1][endIndex], dp[startIndex][endIndex - 1])
startIndex:0, endIndex:4 => st[startIndex] !=st[endIndex], so dp[startIndex][endIndex] = max(dp[startIndex + 1][endIndex], dp[startIndex][endIndex - 1])

From the above visualization, we can clearly see that the length of LPS is '3' as shown by dp[0][4].

Here is the code for our bottom-up dynamic programming approach:

java
class Solution {

  public int findLPSLength(String st) {
    // dp[i][j] stores the length of LPS from index 'i' to index 'j'
    int[][] dp = new int[st.length()][st.length()];

    // every sequence with one element is a palindrome of length 1
    for (int i = 0; i < st.length(); i++) dp[i][i] = 1;

    for (int startIndex = st.length() - 1; startIndex >= 0; startIndex--) {
      for (int endIndex = startIndex + 1; endIndex < st.length(); endIndex++) {
        // case 1: elements at the beginning and the end are the same
        if (st.charAt(startIndex) == st.charAt(endIndex)) {
          dp[startIndex][endIndex] = 2 + dp[startIndex + 1][endIndex - 1];
        } else { // case 2: skip one element either from the beginning or the end
          dp[startIndex][endIndex] = Math.max(
            dp[startIndex + 1][endIndex],
            dp[startIndex][endIndex - 1]
          );
        }
      }
    }
    return dp[0][st.length() - 1];
  }

  public static void main(String[] args) {
    Solution lps = new Solution();
    System.out.println(lps.findLPSLength("abdbca"));
    System.out.println(lps.findLPSLength("cddpd"));
    System.out.println(lps.findLPSLength("pqr"));
  }
}

The time and space complexity of the above algorithm is , where 'n' is the length of the input sequence.

🎯 STRICT STANDOUT — Solution Longest Palindromic Subsequence

0. Pattern family

Family: DP interval / LCS with reverse

1. Why / judgment (K3)

Standout solution states dp[i][j] in words, transition, and bases before code. Brute exponential is only a foil. Memo top-down and bottom-up length loops are duals. LCS(s, rev(s)) is the same O(n²) idea with a different packaging — teach both.

2. Worked complexity / derivation (K11)

States: O(n²) pairs (i,j). Each O(1) work → Θ(n²) time.
Space Θ(n²); rolling two rows O(n) if iterate lengths carefully.
Recursion without memo: T(n)≥2T(n−1) exponential — page should contrast.

3. Pattern + recognition + when-NOT (K12)

Name: INTERVAL DP LPS

Recognition: dp range; equal ends add 2; else max of shrink left/right.

When-NOT: Manacher / expand-center for substring. Regex. LIS on transformed sequence without care.

4. Edge hand-run (K13)

"bbbab": i,j grow by length; ends b,b → 2+LPS(bba interior)=2+2=4.
"a": dp=1. "ab": max 1. Empty: 0.

5. Interviewer follow-ups & drills

Q1. Base cases?
Model answer: i>j →0; i==j →1.

Q2. Why LCS(rev) works?
Model answer: Common subsequence of s and rev(s) is palindromic in s.

Q3. Recover the string?
Model answer: Parent pointers / rebuild from DP, not only length.

🧩 Pattern · Dynamic Programming

Recognize it: Overlapping subproblems + optimal substructure; “count ways” or “min/max over choices” → memoise or fill a table.

▶ Visualize this problem (step it, predict each fork)
⛶ Open this problem debugger in explore mode
🤖 Don't fully get this? Learn it with Claude

Stuck on Longest Palindromic Subsequence? Open Claude, copy a block below, and it'll teach you this exact concept — visually and interactively.

🪜 Hint ladder (no spoilers)

Progressively stronger hints — you still solve it.

I'm working on the problem **Longest Palindromic Subsequence** (DSA). Give me a HINT LADDER: start with the tiniest nudge, then wait. Only reveal the next, stronger hint when I ask. Do NOT show the full solution unless I type 'show solution'. Keep me doing the thinking. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
🎨 Explain the approach visually

See the technique, not just code.

Explain the optimal approach to **Longest Palindromic Subsequence** with a VISUAL walkthrough: trace it on a small concrete example using ASCII art / a step-by-step diagram, narrate what changes each step, then give time & space complexity with a one-line derivation. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
🔍 Review my solution

Catch bugs, edge cases, sub-optimality.

I'll paste my solution to **Longest Palindromic Subsequence**. Review it for correctness, missed edge cases, and time/space complexity, then coach me toward the optimal — don't just rewrite it. Ask me to paste my code now. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
🔁 Drill the pattern

Lock in recognition with look-alikes.

Give me 2 problems that use the SAME underlying pattern as **Longest Palindromic Subsequence**. For each, let me attempt first, then review my answer and name the trigger signal that reveals the pattern. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.

📝 My notes