Longest Palindromic Subsequence

MediumDynamic Programminginterval dp

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

Given a string s, return the length of the longest subsequence of s that reads the same forwards and backwards. A subsequence keeps the original relative order of the characters it uses but may skip any number of characters, so the chosen characters do not need to be adjacent. Aim for O(n^2) time, where n is the length of s.

Examples

Input: s = "bbbab"
Output: 4
Dropping the "a" leaves "bbbb", a palindrome of length 4.
Input: s = "cbbd"
Output: 2
"bb" is the longest palindromic subsequence.

Constraints

  • 1 <= s.length <= 1000
  • `s` consists only of lowercase English letters

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More interval dp problems