TRT
Sign in
mediumAdvancedLeetCode#interval DP

Longest palindromic subsequence

Find the longest subsequence of a string that reads the same backward, with an interval DP on the string's two ends.

The Runtime Theory Team1 min read
Taught inGrids and stringsPro — members onlyTwo-dimensional DP fills a table whose cells depend on their neighbors above and to the left. On grids it counts or optimizes paths; on two strings, a cell compares two prefixes, which is how diff tools, spell checkers and DNA alignment work.
Solve it

Solving happens on the judge — come back and mark it done

Sample cases

ins = bbbab

out4

ins = cbbd

out2

ins = a

out1

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

  1. dp[i][i] = 1.
  2. Match: dp[i+1][j-1] + 2. Otherwise: max(dp[i+1][j], dp[i][j-1]).
  3. 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.

Not started

Sign in to save your learning progress.

Sign in to save