#516

Longest Palindromic Subsequence

Medium Interval DP

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

Return the length of the longest subsequence of s that is a palindrome.

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: the longest palindrome you can get by deleting letters.

Why this works: dp[i][j] for s[i..j]: equal ends → 2 + inside; otherwise the better of dropping one end.

Example: "bbbab"

"bbbb" → 4

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Filling i in increasing order, which reads cells that aren't computed yet.

Solve on LeetCode ↗
Complexity
  • Time: O(n²).
  • Space: O(n²).
Topic: Dynamic Programming
🎬 Episodes 86–96: video coming soon