Skip to content
BytePatterns

Longest Palindromic Subsequence

MediumDynamic Programming#lcs#2d-dp~30m

Problem

Given a string s, return the length of its longest palindromic subsequence: the longest palindrome you can get by deleting any characters from s while keeping the rest in their original order. The kept letters do not need to be next to each other in s.

Examples

Input:  s = "character"
Output: 5
Why:    "carac" keeps c, a, r, a, c in order and reads the same both ways
Input:  s = "abcd"
Output: 1
Why:    no letter repeats, so a single letter is the best
Input:  s = ""
Output: 0
Why:    edge case, nothing to keep

Hints

0 / 3

Stuck on the idea rather than the code? Longest Common Subsequence covers it.