VOOZH about

URL: https://www.geeksforgeeks.org/dsa/longest-palindromic-substring-using-dynamic-programming-2/

⇱ Longest Palindromic Substring using Dynamic Programming - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Longest Palindromic Substring using Dynamic Programming

Last Updated : 23 Jul, 2025

Given a string s, the task is to find the longest substring which is a palindrome. If there are multiple answers, then return the first occurrence of the longest palindromic substring from left to right.

Examples:

Input: s = "aaaabbaa"
Output: "aabbaa"
Explanation: The longest palindromic substring is "aabbaa".

Input: s = "geeks" 
Output: "ee"

Input: s = "abc" 
Output: "a"

Input: s = "" 
Output: ""

Approach:

The idea is to use Dynamic Programming to store the status of smaller substrings and use these results to check if a longer substring forms a palindrome. If we know the status (i.e., palindrome or not) of the substring ranging [i, j], we can find the status of the substring ranging [i-1, j+1] by only matching the character s[i-1] and s[j+1].

  • If the substring from i to j is not a palindrome, then the substring from i-1 to j+1 will also not be a palindrome. Otherwise, it will be a palindrome only if s[i-1] and s[j+1] are the same.

Based on this fact, we can create a 2D table (say dp[][] which stores status of substring s[i...j] ), and check for substrings with length from 1 to n. For each length find all the substrings starting from each character i and find if it is a palindrome or not using the above idea. The longest length for which a palindrome formed will be the required answer.

Illustration:

Follow the below illustration for a better understanding.

Consider the string "geeks". Below is the structure of the table formed and from this, we can see that the longest substring is 2.


Step by step approach:

  1. Maintain a boolean dp[n][n] that is filled in a bottom-up manner.
  2. Fill the table initially for substrings of length = 1 and length = 2 (All substrings of length 1 are palindrome and all substrings of length 2 with same characters are also palindrome).
  3. Iterate for all possible lengths from 3 to n:
    • For each length iterate from i = 0 to n-length, find the end of the substring j = i+length-1. To calculate table[i][j], check the value of table[i+1][j-1]:
      • if the value is true and str[i] is the same as str[j], then we make table[i][j] true.
      • Otherwise, the value of table[i][j] is made false.
  4. Update the longest palindrome accordingly whenever a new palindrome of greater length is found.

Output
aabbaa

Time Complexity: O(n^2)
Auxiliary Space: O(n^2)

Related Articles:

Comment