1. 2D Dynamic Programming Table
Intuition
Let dp[i][j] be true if s[i...j] is a palindrome. A substring s[i...j] is a palindrome if s[i] == s[j] and either j - i <= 2 or dp[i+1][j-1] is true. Fill the table for lengths from 1 to N, tracking the maximum length and start index.
When to apply: When laying out the DP state transition for substring palindromes.
Algorithm
- Initialize
dp[n][n] = false. - Set
start = 0, maxLen = 1. - Loop
lenfrom 1 ton: - Loop
ifrom 0 ton - len: -
j = i + len - 1 - If
s[i] == s[j]and (len <= 2ordp[i + 1][j - 1]): -
dp[i][j] = true - If
len > maxLen:maxLen = len, start = i. - Return
s.substr(start, maxLen).
2D Dynamic Programming Table
2 of 2 questions left todayObservation: Define boolean table isPal[i][j] indicating if s[i
Observation: Define boolean table isPal[i][j] indicating if s[i..j] is palindromic.
Decision: Base case: Every single letter is palindromic. Set isPal[i][i] = true and initialize maxLen = 1.
Invariant: All 1-length substrings satisfy the palindrome definition trivially.
#include <iostream>#include <string>#include <vector> class Solution {public: std::string longestPalindrome(std::string s) { int n = s.size(); if (n <= 1) return s; std::vector<std::vector<bool>> dp(n, std::vector<bool>(n, false)); int start = 0, maxLen = 1; for (int i = 0; i < n; ++i) dp[i][i] = true; for (int len = 2; len <= n; ++len) { for (int i = 0; i <= n - len; ++i) { int j = i + len - 1; if (s[i] == s[j]) { if (len == 2 || dp[i + 1][j - 1]) { dp[i][j] = true; if (len > maxLen) { start = i; maxLen = len; } } } } } return s.substr(start, maxLen); }}; int main() { Solution sol; std::cout << sol.longestPalindrome("babad") << std::endl; // "bab" or "aba" std::cout << sol.longestPalindrome("cbbd") << std::endl; // "bb" return 0;}Time & Space Complexity
- Time complexity:
O(N^2)— Fills an N x N boolean matrix. - Space complexity:
O(N^2)
Why Brute Force Doesn't Scale:
Expanding around centers avoids allocating an N x N DP table, reducing space to O(1).
Manacher's Algorithm provides strictly linear O(N) time with minimal auxiliary memory.