LeetCode #516 Medium

Longest Palindromic Subsequence

Longest Palindromic Subsequence is LeetCode 516 (Medium). Given a string s, return the length of the longest subsequence of s that reads the same forwards and backwards.

A subsequence keeps the letters in their original order but may skip any of them, so the palindrome does not have to be one unbroken block.

Constraints
  • 1 <= s.length <= 1000
  • s consists only of lowercase English letters.
stringdynamic programming
Open on LeetCode ↗
02

Intuition

Work on a range of the string, from index i to index j, and look only at its two end letters.

  • Ends equal: they can be the outer pair of a palindrome. Wrap them around the best palindrome strictly inside, which adds 2.
  • Ends differ: no palindrome can use both, because its first and last letters would differ. Drop the left end or the right end and keep the better result.

Every range depends only on shorter ranges inside it, so filling the answers from short ranges to long ones solves the whole string in O(n²).

03

Approach

1

Define one cell per range

Let dp[i][j] be the answer for s[i..j], both ends included. Only cells with i <= j are used, so the table is a triangle. A single letter is a palindrome on its own, so dp[i][i] = 1.

2

Fill a range from its two ends

  • If s[i] == s[j]: dp[i][j] = dp[i+1][j-1] + 2.
  • Otherwise: dp[i][j] = max(dp[i+1][j], dp[i][j-1]).

When j = i + 1 the inside range is empty, and the zero already stored at dp[i+1][i] is the right value for it.

3

Fill rows from the bottom up

A cell reads row i + 1, so run i from n - 1 down to 0, and j from i + 1 up to n - 1. That way every shorter range is finished before a longer one needs it. The answer is dp[0][n-1], the whole string.

4

Rebuild the palindrome if you need the letters

Start with the whole range. When the ends match, put that letter on both sides of the result and move both ends inwards. Otherwise move the end whose side holds the larger value. A single leftover letter becomes the middle.

5

Keep two rows to save memory

Row i reads only itself and row i + 1, so two arrays of length n give O(n) space when only the length is needed.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def longestPalindromeSubseq(self, s: str) -> int:
▶3 n = len(s)
▶4 dp = [[0] * n for _ in range(n)]
▶5 for i in range(n - 1, -1, -1):
▶6 dp[i][i] = 1
▶7 for j in range(i + 1, n):
▶8 if s[i] == s[j]:
▶9 dp[i][j] = dp[i + 1][j - 1] + 2
▶10 else:
▶11 dp[i][j] = max(dp[i + 1][j], dp[i][j - 1])
▶12 return dp[0][n - 1]
bbbabthis rangenot startedpalindromeone cell for every range of letters
ranges15row L of the pyramid holds ranges of L letters
One cell per range. Each cell sits right under the letters it covers: the top row is single letters, the bottom cell is the whole string. A range only needs answers for shorter ranges inside it, and those are the cells above it.
bbbabij1this rangebone letter→1lengthpalindrome'b' alone is a palindrome → 1
range"b"
value1
Row 4 starts with its single letter. One letter reads the same both ways, so its answer is 1. Rows run from the right end of the string to the left, because a range starting at i reads ranges starting at i + 1.
bbbaijb11this rangeaone letter→1lengthpalindrome'a' alone is a palindrome → 1
range"a"
value1
Row 3 starts with its single letter. One letter reads the same both ways, so its answer is 1. Rows run from the right end to the left, so every range starting at 4 is already finished when this row needs it.
bbbaibj111this range1drop left1drop right→1palindrome'a' ≠ 'b' → drop one end, keep 1
range"ab"
value1
The ends differ, and a palindrome's first and last letters must be equal, so this range cannot use both. Without 'a' the best is 1, without 'b' it is 1. Keep the larger: 1.
bbbijab1111this rangebone letter→1lengthpalindrome'b' alone is a palindrome → 1
range"b"
value1
Row 2 starts with its single letter. One letter reads the same both ways, so its answer is 1. Rows run from the right end to the left, so every range starting at 3 is already finished when this row needs it.
bbbiajb11111this range1drop left1drop right→1palindrome'b' ≠ 'a' → drop one end, keep 1
range"ba"
value1
The ends differ, and a palindrome's first and last letters must be equal, so this range cannot use both. Without 'b' the best is 1, without 'a' it is 1. Keep the larger: 1.
bbbiabj113111this range1inside+2both ends=3palindromeboth ends are 'b' → wrap them round the inside
range"bab"
value3
The two ends are the same letter, so they can be the outside pair of a palindrome. The best palindrome strictly inside is 1, and wrapping the pair round it adds 2: 3.
bbijbab1113111this rangebone letter→1lengthpalindrome'b' alone is a palindrome → 1
range"b"
value1
Row 1 starts with its single letter. One letter reads the same both ways, so its answer is 1. Rows run from the right end to the left, so every range starting at 2 is already finished when this row needs it.
bbibjab12113111this range0inside+2both ends=2palindromeboth ends are 'b' → wrap them round the inside
range"bb"
value2
The two ends are the same letter, so they can be the outside pair of a palindrome. The best palindrome strictly inside is empty (0), and wrapping the pair round it adds 2: 2.
bbibajb122113111this range1drop left2drop right→2palindrome'b' ≠ 'a' → drop one end, keep 2
range"bba"
value2
The ends differ, and a palindrome's first and last letters must be equal, so this range cannot use both. Without 'b' the best is 1, without 'a' it is 2. Keep the larger: 2.
bbibabj1223113111this range1inside+2both ends=3palindromeboth ends are 'b' → wrap them round the inside
range"bbab"
value3
The two ends are the same letter, so they can be the outside pair of a palindrome. The best palindrome strictly inside is 1, and wrapping the pair round it adds 2: 3.
bijbbab11223113111this rangebone letter→1lengthpalindrome'b' alone is a palindrome → 1
range"b"
value1
Row 0 starts with its single letter. One letter reads the same both ways, so its answer is 1. Rows run from the right end to the left, so every range starting at 1 is already finished when this row needs it.
bibjbab121223113111this range0inside+2both ends=2palindromeboth ends are 'b' → wrap them round the inside
range"bb"
value2
The two ends are the same letter, so they can be the outside pair of a palindrome. The best palindrome strictly inside is empty (0), and wrapping the pair round it adds 2: 2.
bibbjab1231223113111this range1inside+2both ends=3palindromeboth ends are 'b' → wrap them round the inside
range"bbb"
value3
The two ends are the same letter, so they can be the outside pair of a palindrome. The best palindrome strictly inside is 1, and wrapping the pair round it adds 2: 3.
bibbajb12331223113111this range2drop left3drop right→3palindrome'b' ≠ 'a' → drop one end, keep 3
range"bbba"
value3
The ends differ, and a palindrome's first and last letters must be equal, so this range cannot use both. Without 'b' the best is 2, without 'a' it is 3. Keep the larger: 3.
bibbabj123341223113111this range2inside+2both ends=4palindromeboth ends are 'b' → wrap them round the inside
range"bbbab"
value4
The two ends are the same letter, so they can be the outside pair of a palindrome. The best palindrome strictly inside is 2, and wrapping the pair round it adds 2: 4.
bibbabj123341223113111this rangerebuildingpalindromebbends match → 'b' goes on both sides
range"bbbab"
letters placed2 of 4
Printing the palindrome. The length alone does not say which letters to keep, but each cell remembers how it was made. Matching ends go on both sides of the result; otherwise move to whichever shorter range kept the larger value, because that is where this cell's number came from.
bbibajb123341223113111this rangerebuildingpalindromebb'b' ≠ 'a' → the 2 came from dropping 'a'
range"bba"
letters placed2 of 4
Printing the palindrome. The length alone does not say which letters to keep, but each cell remembers how it was made. Matching ends go on both sides of the result; otherwise move to whichever shorter range kept the larger value, because that is where this cell's number came from.
bbibjab123341223113111this rangerebuildingpalindromebbbbends match → 'b' goes on both sides
range"bb"
letters placed4 of 4
Printing the palindrome. The length alone does not say which letters to keep, but each cell remembers how it was made. Matching ends go on both sides of the result; otherwise move to whichever shorter range kept the larger value, because that is where this cell's number came from.
bbbab123341223113111this rangefinishedpalindromebbbbanswer: 4, for example "bbbb"
answer4bottom cell, the whole string
one palindrome"bbbb"
Answer 4. The bottom cell covers the whole string. The walk placed exactly 4 letters, two for each matching pair of ends and one for a leftover middle letter.
05

Common pitfalls

Filling rows from the top down

✗ Wrong
for i in range(n):
    dp[i][i] = 1
    for j in range(i + 1, n):
✓ Right
for i in range(n - 1, -1, -1):
    dp[i][i] = 1
    for j in range(i + 1, n):

Row i reads row i + 1, which top-down order has not filled yet, so it reads zeros. On "bbbab" the wrong order returns 2 instead of 4, with no error to warn you.

Answering the substring question instead

✗ Wrong
only counting ranges that are palindromes themselves
✓ Right
letting a mismatch drop one end and keep the inside

A subsequence may skip letters. On "bbbab" the longest palindromic substring is "bbb" (3), but skipping the a gives "bbbb" (4).

06

Edge cases

All letters different, e.g. "abcd"

No pair of ends ever matches, so every range keeps the value of its best single letter and the answer is 1.

07

Complexity

Time
O(n²)
Space
O(n²)
About n²/2 ranges, each filled in constant time. Two rows bring space down to O(n), but rebuilding the letters needs the full triangle.
08

Longest Palindromic Subsequence FAQ

Can I solve it with LCS on the string and its reverse?

Yes. A palindrome reads the same both ways, so any palindromic subsequence of s also appears in reversed s, and the longest subsequence the two share has the same length as the longest palindrome. For "bbbab" and "babbb" that gives 4. See Longest Common Subsequence for that table. It costs the same O(n²) but fills a full square instead of a triangle.

How many insertions make a string a palindrome?

n minus this answer. The letters in the longest palindromic subsequence can stay, and every other letter needs a mirror copy inserted. "mbadm" has length 5 and answer 3 ("mam"), so 2 insertions are enough. That is Minimum Insertion Steps to Make a String Palindrome.