Return the length of the longest palindromic subsequence of s.
Before you code
dp[i][j] is the answer for s[i..j]. Compare the two ends: if they match, both can be the outer layer of the palindrome.
Hints
- dp[i][i] = 1.
- Match:
dp[i+1][j-1] + 2. Otherwise:max(dp[i+1][j], dp[i][j-1]). - Fill by increasing length, or i from n − 1 down to 0. It also equals the LCS of s and its reverse.
Production & complexity notes
When solving Longest palindromic subsequence on LeetCode (medium), always state your loop or recursion invariant before writing code. Verify how your chosen data structure behaves on degenerate inputs (single-element inputs, all-duplicate keys, strictly monotonic sequences, or maximum constraint sizes up to $10^5$ elements). In production interviews, pair your implementation with an explicit time and auxiliary space complexity proof, explain why alternative brute-force approaches violate the latency budget, and trace how cache locality and memory allocation overhead affect wall-clock throughput on real hardware. Review the step-by-step memory trace in Grids and strings to reinforce the underlying pattern.
What it practices
Tables over intervals of one string, from Grids and strings.