πDay 4. Longest Palindromic Subsequence π§
The problem can be found at the following link: Question Link
π‘ Problem Description:
Given a string s, return the length of the longest palindromic subsequence.
A subsequence is a sequence derived from the given sequence by deleting some or no elements without changing the order of the remaining elements. A palindromic subsequence reads the same forwards and backwards.
π Example Walkthrough:
Example 1:
Input:
s = "bbabcbcab"
Output:
7
Explanation:
The longest palindromic subsequence is "babcbab", which has a length of 7.
Example 2:
Input:
s = "abcd"
Output:
1
Explanation:
The longest palindromic subsequence is any single character, which has a length of 1.
Example 3:
Input:
s = "agbdba"
Output:
5
Explanation:
The longest palindromic subsequence is "abdba", which has a length of 5.
Constraints:
$1 \leq s.size() \leq 1000$
The string contains only lowercase letters.
π― My Approach:
DP - Bottom-Up 2D Table
Algorithm Steps:
Create a 2D DP table, where
dp[i][j]stores the length of the longest palindromic subsequence in substrings[i...j].Initialize diagonal elements (
dp[i][i]) to 1, since a single character is always a palindrome of length 1.Iterate over substrings of increasing lengths.
For each substring
s[i...j]:If
s[i] == s[j], the length extends by 2 (both characters can form a palindrome around the inner subsequences[i+1...j-1]).Otherwise, take the maximum palindromic subsequence length by either excluding
s[i]or excludings[j].
Final answer is stored in
dp[0][n-1]β the longest palindromic subsequence in the entire string.
π Time and Auxiliary Space Complexity
Expected Time Complexity: $O(N^2)$, as we fill a 2D DP table for all substrings, and each cell is filled in constant time.
Expected Auxiliary Space Complexity: $O(N^2)$, for storing the DP table, which tracks the longest palindromic subsequence length for each substring.
π Solution Code
Code (C++)
Code (Java)
Code (Python)
π― Contribution and Support:
For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: Any Questions. Letβs make this learning journey more collaborative!
β If you find this helpful, please give this repository a star! β
πVisitor Count
Last updated