Home  Dsa   Dynamic pro ...

Dynamic Programming (DP) approach for the Longest Palindromic Substring problem and solution in Java and Python

Let’s go through the Dynamic Programming (DP) approach for the Longest Palindromic Substring problem — with a clear explanation, example table, and Java/Python code.


🧩 Problem Recap

Find the longest palindromic substring in a given string s.

Example:

Input:  "babad"
Output: "bab" or "aba"

💡 Dynamic Programming Approach

🧠 Key Idea

We define:

dp[i][j] = true  if the substring s[i...j] is a palindrome

So:


🪜 Steps

  1. Create a 2D DP table (n x n) initialized to false

  2. Mark all single letters as true

  3. Expand substring length from 2 → n:

    • If the current substring s[i...j] is a palindrome → mark it
    • Keep track of the longest one

🧮 Example:

s = "babad"

i\j0 (b)1 (a)2 (b)3 (a)4 (d)
0 (b)TFTFF
1 (a)TFTF
2 (b)TFF
3 (a)TF
4 (d)T

Here "bab" and "aba" are both valid palindromic substrings.


Java Solution (DP)

class Solution {
    public String longestPalindrome(String s) {
        int n = s.length();
        if (n < 2) return s;

        boolean[][] dp = new boolean[n][n];
        int start = 0, maxLen = 1;

        // Every single character is palindrome
        for (int i = 0; i < n; i++)
            dp[i][i] = true;

        // Fill DP table
        for (int len = 2; len <= n; len++) {
            for (int i = 0; i <= n - len; i++) {
                int j = i + len - 1;

                if (s.charAt(i) == s.charAt(j)) {
                    if (len == 2 || dp[i + 1][j - 1]) {
                        dp[i][j] = true;
                        if (len > maxLen) {
                            start = i;
                            maxLen = len;
                        }
                    }
                }
            }
        }
        return s.substring(start, start + maxLen);
    }
}

Python Solution (DP)

def longestPalindrome(s: str) -> str:
    n = len(s)
    if n < 2:
        return s

    dp = [[False] * n for _ in range(n)]
    start, max_len = 0, 1

    # Each character is palindrome
    for i in range(n):
        dp[i][i] = True

    # Build table
    for length in range(2, n + 1):
        for i in range(n - length + 1):
            j = i + length - 1
            if s[i] == s[j]:
                if length == 2 or dp[i + 1][j - 1]:
                    dp[i][j] = True
                    if length > max_len:
                        start = i
                        max_len = length

    return s[start:start + max_len]

⚖️ Complexity

OperationTimeSpace
Dynamic ProgrammingO(n²)O(n²)

🎯 When to Use Which

MethodBest WhenComplexity
Expand Around CenterSimpler, O(1) spaceO(n²)
Dynamic ProgrammingTeaching/trace visualizationO(n²) time, O(n²) space
Manacher’s AlgorithmAdvanced, very fastO(n) time

🧠 Analogy

Imagine marking matching mirrors in a word: Whenever the letters at both ends match, you “light up” that substring in your table. The longest lit-up area = your longest palindrome ✨


Published on: Oct 11, 2025, 10:22 PM  
 

Comments

Add your comment