Given a string s, find the longest palindromic subsequence within it and return its length.
A subsequence is derived from a string by deleting some or no characters without changing the order of the remaining characters. Unlike substrings, subsequences don't need to be contiguous.
What makes this challenging? A palindrome reads the same forwards and backwards (like "racecar"). You need to find the longest possible palindrome you can form by picking characters from the original string while maintaining their relative order.
Example: In the string "bbbab", you can pick characters at positions 0,1,2 and 4 to form "bbbb" (length 4), which is the longest palindromic subsequence.
Input & Output
Visualization
Time & Space Complexity
We fill an nĆn DP table, each cell taking O(1) time to compute
DP table of size nĆn to store intermediate results
Constraints
- 1 ⤠s.length ⤠1000
- s consists only of lowercase English letters
- Note: Subsequences don't need to be contiguous