oneby7

2-D Dynamic Programming Two strings

561. Longest Palindromic Subsequence

Medium

You are given a string s. Return the length of its longest subsequence that is a palindrome.

A subsequence is what is left after deleting some letters of s, or none, without changing the order of the rest. Its letters do not have to sit next to each other. A palindrome reads the same forwards and backwards, such as "level" or "noon".

A single letter is a palindrome, so the answer is always at least 1.

Example 1

Input: s = "character"

Output: 5

Explanation: Keeping the letters at indexes 0, 2, 3, 4 and 5 gives carac, which reads the same both ways. No 6 letters of s form a palindrome.

Example 2

Input: s = "xyz"

Output: 1

Explanation: No letter repeats, so every palindrome here is a single letter.

Example 3

Input: s = "cbbdc"

Output: 4

Explanation: cbbc skips the d. It has an even length, with two equal letters in the middle.

Check your understanding

Work out the answer for this input before you write any code.

s = "abcab"

Constraints

  • 1 ≤ s.length ≤ 3000
  • s holds only lowercase English letters.

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.