iq.lab
Python starts when a code cell comes near or you run one
mediumDynamic programming, 2D target 25 min

Longest palindromic subsequence

You get a string s of lowercase letters. A subsequence keeps some of the letters in their original order and drops the rest. A palindrome reads the same forward and backward, like "level".

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

Example 1
Inputs = "agbcba"Output5

Dropping the g leaves "abcba".

Example 2
Inputs = "abcd"Output1

No letter repeats, so the best palindrome is a single letter.

Example 3
Inputs = "character"Output5

One answer is "carac", from the letters at positions 0, 2, 3, 4 and 5.

Constraints
  • 1 ≤ len(s) ≤ 1,000

  • s holds only lowercase English letters.

Plan it first

Write a line for each before you code, then say them out loud. Compare with the Approach tab afterwards.

⌘+Enter runs 0:00Python starts when a code cell comes near or you run one
Run examples checks the examples. Submit runs every test, including edge cases and, when the problem has one, a speed check on a large input.