Longest Palindromic Substring in Python

Finding the longest palindromic substring in a string is a classic dynamic programming problem. A palindrome reads the same forwards and backwards, like "BAB" or "RACECAR". We'll use a 2D table to track which substrings are palindromes.

Algorithm Overview

The approach uses dynamic programming with these steps ?

  • Create a 2D boolean matrix where dp[i][j] represents if substring from index i to j is a palindrome
  • Initialize single characters as palindromes (diagonal elements = True)
  • Check substrings of increasing length, starting from length 2
  • For each substring, check if first and last characters match and the inner substring is a palindrome
  • Track the longest palindrome found

Dynamic Programming Solution

class Solution:
    def longestPalindrome(self, s):
        n = len(s)
        # dp[i][j] will be True if substring s[i:j+1] is palindrome
        dp = [[False for _ in range(n)] for _ in range(n)]
        
        # All single characters are palindromes
        for i in range(n):
            dp[i][i] = True
        
        max_length = 1
        start = 0
        
        # Check for substrings of length 2 to n
        for length in range(2, n + 1):
            for i in range(n - length + 1):
                end = i + length - 1
                
                if length == 2:
                    # For length 2, just check if both characters are same
                    if s[i] == s[end]:
                        dp[i][end] = True
                        max_length = length
                        start = i
                else:
                    # For length > 2, check if first and last chars match
                    # and the substring between them is palindrome
                    if s[i] == s[end] and dp[i + 1][end - 1]:
                        dp[i][end] = True
                        max_length = length
                        start = i
        
        return s[start:start + max_length]

# Test the solution
solution = Solution()
result = solution.longestPalindrome("ABBABBC")
print(f"Input: 'ABBABBC'")
print(f"Longest palindromic substring: '{result}'")
Input: 'ABBABBC'
Longest palindromic substring: 'BBABB'

How It Works

Let's trace through the algorithm with string "ABBABBC" ?

def longestPalindromeWithTrace(s):
    n = len(s)
    dp = [[False for _ in range(n)] for _ in range(n)]
    
    # Initialize single characters
    for i in range(n):
        dp[i][i] = True
    
    max_length = 1
    start = 0
    print(f"String: {s}")
    print("Checking substrings:")
    
    for length in range(2, n + 1):
        for i in range(n - length + 1):
            end = i + length - 1
            substring = s[i:end + 1]
            
            if length == 2:
                if s[i] == s[end]:
                    dp[i][end] = True
                    max_length = length
                    start = i
                    print(f"  '{substring}' is palindrome (length {length})")
            else:
                if s[i] == s[end] and dp[i + 1][end - 1]:
                    dp[i][end] = True
                    max_length = length
                    start = i
                    print(f"  '{substring}' is palindrome (length {length})")
    
    return s[start:start + max_length]

result = longestPalindromeWithTrace("ABBABBC")
print(f"\nLongest palindrome: '{result}'")
String: ABBABBC
Checking substrings:
  'BB' is palindrome (length 2)
  'ABA' is palindrome (length 3)
  'BBABB' is palindrome (length 5)

Longest palindrome: 'BBABB'

Alternative Examples

solution = Solution()

# Test with different strings
test_cases = ["BABAC", "racecar", "abcd", "aabbaa"]

for test in test_cases:
    result = solution.longestPalindrome(test)
    print(f"'{test}' → '{result}'")
'BABAC' ? 'BAB'
'racecar' ? 'racecar'
'abcd' ? 'a'
'aabbaa' ? 'aabbaa'

Time and Space Complexity

  • Time Complexity: O(n²) where n is the length of the string
  • Space Complexity: O(n²) for the 2D DP table

Conclusion

The dynamic programming approach efficiently finds the longest palindromic substring by building up solutions from smaller subproblems. It checks all possible substrings systematically and maintains a table to avoid recomputation, making it optimal for this problem.

Updated on: 2026-03-25T07:39:10+05:30

11K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements