Leetcode 516: Longest Palindromic Subsequence

grid47
grid47
Exploring patterns and algorithms
Sep 16, 2024 6 min read

A string where the longest palindromic subsequence is highlighted, glowing as it mirrors itself.
Solution to LeetCode 516: Longest Palindromic Subsequence Problem

Given a string s, return the length of the longest palindromic subsequence in s. A subsequence is a sequence derived by deleting some or no elements without changing the order of the remaining elements.
Problem
Approach
Steps
Complexity
Input: The input is a string `s` consisting of lowercase English letters.
Example: s = "aabca"
Constraints:
• 1 <= s.length <= 1000
• s consists only of lowercase English letters.
Output: The output should be an integer representing the length of the longest palindromic subsequence in `s`.
Example: 3
Constraints:
• The output should be a single integer.
Goal: To find the length of the longest subsequence in `s` that is a palindrome.
Steps:
• 1. Use dynamic programming to store intermediate results.
• 2. For each pair of indices `i` and `j`, check if the characters match.
• 3. If the characters match, consider the longest subsequence between `i+1` and `j-1`, and add 2.
• 4. If the characters don't match, take the maximum value between `dp(i + 1, j)` and `dp(i, j - 1)`.
Goal: The string `s` will be between 1 and 1000 characters long, and will only contain lowercase letters.
Steps:
• 1 <= s.length <= 1000
• s consists only of lowercase English letters.
Assumptions:
• The string `s` is not empty unless specified.
• The input string contains only lowercase English letters.
Input: s = "aabca"
Explanation: The longest palindromic subsequence in the string 'aabca' is 'aba', which has a length of 3.

Input: s = "abcde"
Explanation: Since no characters repeat, the longest palindromic subsequence is any single character, with a length of 1.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus