πΉ Key Idea (VERY IMPORTANT π₯)
π Convert LPS β LCS
LPS(s) = LCS(s, reverse(s))
πΉ Why does this work?
- Palindrome = same forward & backward
- So if we reverse string and find LCS β we get longest palindrome subsequence
πΉ Your Code Explained
string t = s;
reverse(t.begin(), t.end());
return lcs(s, t);
π Steps:
- Copy string β
t - Reverse it
- Find LCS between
sandt
πΉ Example
s = "bbabcbcab"
Reverse:
t = "bacbcbabb"
π LCS = "babcbab" (length = 7)
π₯ Full Code (Clean)
int lcs(string s1, string s2) {
int n = s1.size(), m = s2.size();
vector<vector<int>> dp(n+1, vector<int>(m+1, 0));
for(int i = 1; i <= n; i++){
for(int j = 1; j <= m; j++){
if(s1[i-1] == s2[j-1])
dp[i][j] = 1 + dp[i-1][j-1];
else
dp[i][j] = max(dp[i-1][j], dp[i][j-1]);
}
}
return dp[n][m];
}
int longestPalindromeSubsequence(string s) {
string t = s;
reverse(t.begin(), t.end());
return lcs(s, t);
}
πΉ Space Optimized Version π
int lcs(string s1, string s2) {
int n = s1.size(), m = s2.size();
vector<int> prev(m+1, 0), curr(m+1, 0);
for(int i = 1; i <= n; i++){
for(int j = 1; j <= m; j++){
if(s1[i-1] == s2[j-1])
curr[j] = 1 + prev[j-1];
else
curr[j] = max(prev[j], curr[j-1]);
}
prev = curr;
}
return prev[m];
}
π₯ Print Longest Palindromic Subsequence
π Just print LCS of s and reverse(s)
string printLPS(string s) {
string t = s;
reverse(t.begin(), t.end());
int n = s.size();
vector<vector<int>> dp(n+1, vector<int>(n+1, 0));
for(int i=1;i<=n;i++){
for(int j=1;j<=n;j++){
if(s[i-1]==t[j-1])
dp[i][j]=1+dp[i-1][j-1];
else
dp[i][j]=max(dp[i-1][j],dp[i][j-1]);
}
}
// backtrack
string ans="";
int i=n,j=n;
while(i>0 && j>0){
if(s[i-1]==t[j-1]){
ans+=s[i-1];
i--; j--;
}
else if(dp[i-1][j]>dp[i][j-1]) i--;
else j--;
}
reverse(ans.begin(), ans.end());
return ans;
}
πΉ Complexity
| Metric | Value |
|---|---|
| Time | O(nΒ²) |
| Space | O(nΒ²) β optimized to O(n) |
π§ Important Observations
- LPS is a subsequence, not substring
- Works even if characters are not continuous
- Always think:
βReverse + LCSβ
π₯ Related Problems
- Minimum insertions to make palindrome:
n - LPS
- Minimum deletions:
n - LPS
β‘ Interview Tip
If asked:
βLongest palindromic subsequence?β
π Say instantly:
βWe can solve it using LCS between string and its reverse.β
If you want next π
I can show:
β
Direct DP without LCS trick
β
Palindromic substring (different problem β οΈ)
β
Hard variations
Just tell me π
Top comments (0)