Algo-Sim › Dynamic Programming

Longest Palindromic Substring

Medium · Dynamic Programming · step through it in Java, Python and C++ on your own input

Find the longest contiguous substring that reads the same forwards and backwards.

Problem

Given a string s, return the longest contiguous substring of s that reads the same forwards and backwards. If several have the same length, any of them is accepted.

Constraints

Edge cases to test

Follow-up questions

Expand around centres or DP?
Expanding is O(n²) time and O(1) space; the DP table is also O(n²) time but O(n²) space.
Can it be linear?
Manacher’s algorithm reuses mirrored radii: O(n).

Solution

Java

public String longestPalindrome(String s) {
    int n = s.length(), start = 0, maxLen = 1;
    boolean[][] dp = new boolean[n][n];
    for (int i = 0; i < n; i++) dp[i][i] = true;
    for (int len = 2; len <= n; len++) {
        for (int i = 0; i + len - 1 < n; i++) {
            int j = i + len - 1;
            dp[i][j] = s.charAt(i) == s.charAt(j) && (len == 2 || dp[i + 1][j - 1]);
            if (dp[i][j] && len > maxLen) {
                start = i;
                maxLen = len;
            }
        }
    }
    return s.substring(start, start + maxLen);
}

Python

def longest_palindrome(s):
    n, start, max_len = len(s), 0, 1
    dp = [[False] * n for _ in range(n)]
    for i in range(n):
        dp[i][i] = True
    for length in range(2, n + 1):
        for i in range(n - length + 1):
            j = i + length - 1
            dp[i][j] = s[i] == s[j] and (length == 2 or dp[i + 1][j - 1])
            if dp[i][j] and length > max_len:
                start = i
                max_len = length
    return s[start:start + max_len]

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    string longestPalindrome(string &s) {
        int n = int(s.size()), start = 0, maxLen = 1;
        vector<vector<bool>> dp = vector<vector<bool>>(n, vector<bool>(n));
        for (int i = 0; i < n; i++)
            dp[i][i] = true;
        for (int len = 2; len <= n; len++) {
            for (int i = 0; i + len - 1 < n; i++) {
                int j = i + len - 1;
                dp[i][j] = s[i] == s[j] && (len == 2 || dp[i + 1][j - 1]);
                if (dp[i][j] && len > maxLen) {
                    start = i;
                    maxLen = len;
                }
            }
        }
        return s.substr(start, (start + maxLen) - (start));
    }
};

More Dynamic Programming problems