101 Logo
onenoughtone

Problem Statement

Palindromic Subsequence Finder

You are a linguist studying ancient texts that may contain hidden palindromic messages. In these texts, the meaningful messages are often formed by taking certain characters (not necessarily consecutive) while maintaining their relative order.

Given a string s, your task is to find the longest subsequence that forms a palindrome. A subsequence is a sequence that can be derived from the original string by deleting some or no characters without changing the order of the remaining characters.

For example, in the word "linguistics", the subsequence "inis" forms a palindrome, as do "ini" and "i", but "inis" is the longest.

Examples

Example 1:

Input: s = "bbbab"
Output: 4
Explanation: The longest palindromic subsequence is 'bbbb', which has a length of 4.

Example 2:

Input: s = "cbbd"
Output: 2
Explanation: The longest palindromic subsequence is 'bb', which has a length of 2.

Example 3:

Input: s = "linguistics"
Output: 3
Explanation: The longest palindromic subsequence is 'ini', which has a length of 3.

Constraints

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

Problem Breakdown

To solve this problem, we need to:

  1. A palindrome reads the same forward and backward, so we need to find characters that can be arranged symmetrically.
  2. The longest palindromic subsequence problem can be solved using dynamic programming.
  3. If the first and last characters of a string are the same, they can be part of the palindromic subsequence.
  4. We can build up the solution by considering subproblems of different substring lengths.
ProblemSolutionCode
101 Logo
onenoughtone