Longest Palindromic Subsequence

MediumString DP · Interval (i, j)🧩 String DPLeetCode #516 ↗Updated

Problem

Given a string s, return the length of its longest subsequence (delete any characters, keep the order of the rest) that reads the same forwards and backwards.
Input"bbbab"Output4 ("bbbb")
Input"cbbd"Output2 ("bb")

1 ≤ s.length ≤ 1000  ·  lowercase English letters only

Try it yourself

Java
class Solution {
    public int longestPalindromeSubseq(String s) {
        
    }
}
Your code is saved in this browser.Submit on LeetCode ↗
Key insight
Look at the two ends of s[i..j]: if s[i] == s[j] they wrap the best palindrome inside (2 + f(i+1, j-1)); otherwise one end must be dropped (max(f(i+1, j), f(i, j-1))). Only O(n2) intervals exist.
PatternString DP

Instinct Two strings compared char by char (match, edit, interleave) means dp[i][j] over prefixes; one string's palindromes or splits means dp[l][r] or dp[i].

Memory hack Match? Go diagonal. Mismatch? Ask the neighbours. Up drops a char from s, left drops one from t, diagonal uses both.

Open the String DP guide →

Approaches

Brute ForcePlain Recursion on Intervals

Time O(2n)Space O(n)

f(l, r) = answer for s[l..r]. Empty interval → 0, one char → 1. A mismatch spawns two calls, each only one character shorter, so the call tree doubles per level and recomputes the same intervals.

Java
public int longestPalindromeSubseq(String s) {
    return f(s, 0, s.length() - 1);
}
private int f(String s, int l, int r) {
    if (l > r) return 0;
    if (l == r) return 1;
    if (s.charAt(l) == s.charAt(r)) return 2 + f(s, l + 1, r - 1);
    return Math.max(f(s, l + 1, r), f(s, l, r - 1));
}

Direct translation of the recurrence, but exponential.

At a glance

LevelApproachTimeSpace
Brute ForcePlain Recursion on IntervalsO(2n)O(n)
BetterMemoized Recursion (Top-Down)O(n2)O(n2)
OptimalBottom-Up, One RowO(n2)O(n)
Common pitfalls
  • Mixing up with Longest Palindromic Substring (5) — here gaps are allowed.
  • Filling the 2-D table row-by-row from i = 0 — dp[i+1] isn't ready.
  • Forgetting the base case l == r → 1 (or dp[i] = 1).
Interview tips
  • Frame it as interval DP: state = (left, right), shrink from the ends.
  • Mention the LCS-with-reverse reduction as a quick sanity check.
  • Note the fill order: i descending, j ascending.
Pattern
Interval DP on (i, j) → palindrome/subsequence questions answered by comparing the two ends.
My notes saved in this browser