Longest Palindromic Subsequence?
Short answer: int LongestPalindromeSubseq(string s) { int n = s.Length; int[,] dp = new int[n, n]; for (int i = n - 1; i >= 0; i--) { dp[i, i] = 1; for (int j = i + 1; j < n; j++) { if (s[i] == s[j]) Follow on: dp[i, j] = dp[i + 1, j - 1] + 2; else dp[i, j] = Math.Max(dp[i + 1, j], dp[i, j - 1]); } } return dp[0, n - 1]; }
Example code
int LongestPalindromeSubseq(string s) {
int n = s.Length;
int[,] dp = new int[n, n];
for (int i = n - 1; i >= 0; i--) {
dp[i, i] = 1;
for (int j = i + 1; j < n; j++) {
if (s[i] == s[j]) Follow on: dp[i, j] = dp[i + 1, j - 1] + 2; else dp[i, j] = Math.Max(dp[i + 1, j], dp[i, j - 1]);
}
}
return dp[0, n - 1];
}
Real-world example (ShopNest)
In coding rounds, state complexity aloud, write a clear ShopNest-flavored example (orders, carts), then handle edge cases (empty list, null, overflow).
Say this in the interview
- Define — one clear sentence (the short answer above).
- Example — relate it to a project like ShopNest or your real work.
- Trade-off — when you would not use it.
Share this Q&A
Share preview image: https://www.toolliyo.com/images/toolliyo-logo.png