Longest Palindromic Substring
Longest Palindromic Substring is a medium dynamic programming problem solved with the strings pattern.
The best approach, optimal (expand around each center), runs in O(n²) time and O(1) space.
Below are 3 approaches in Java, Python, C++ and JavaScript, from brute force (check every substring) up.
Problem
Given a string s, return its longest palindromic substring: the longest contiguous block of characters that reads the same from left to right as from right to left.
If more than one block has the maximum length, return any one of them.
Examples
Example 1
- Input
s = "xracecarz"- Output
"racecar"- Why
- "racecar" reads the same in both directions and no longer block does.
Example 2
- Input
s = "abbd"- Output
"bb"- Why
- An even-length palindrome: its center sits between the two b's.
Example 3
- Input
s = "q7"- Output
"q"- Why
- No two neighbors match, so any single character is a valid answer ("7" is accepted too).
Constraints
1 <= s.length <= 1000scontains only English letters and digits.- If several longest palindromes exist, any one of them is accepted.
Solve it here
Write your solution in Java, Python, C++ or JavaScript and run it against the examples, right in the page. Submit runs the hidden tests too and, with a free account, records the solve in your revision log.
Your own testcases: Run checks these, and the expected output comes from our reference solution.
My submissions
Nothing yet. Every Run and Submit you make while signed in shows up here.
| When | Result | Tests | Runtime | Your time | Type |
|---|
Run checks the testcases above (3 examples, or your own). Submit also runs 16 hidden tests and saves the solve to your log. Signed in, every Run and Submit is saved under My submissions; your draft stays in this browser.
Solutions
Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the code in Java, Python, C++ and JavaScript.
| Approach | Time | Space |
|---|---|---|
| Brute force (check every substring) | O(n³) | O(1) |
| Better (DP table) | O(n²) | O(n²) |
| Optimal (expand around each center) | O(n²) | O(1) |
1Brute force (check every substring)
O(n³)O(n²) substrings, each checked in O(n).O(1)Only indices besides the answer.Try every pair of start and end indices, check whether that block is a palindrome with two pointers, and keep the longest one found.
- For every i and every j >= i, test s[i..j] with two pointers moving inward.
- If it is a palindrome and longer than the best so far, record it.
class Solution {
public String longestPalindrome(String s) {
int n = s.length(), bestL = 0, bestLen = 1;
for (int i = 0; i < n; i++) {
for (int j = i + bestLen; j < n; j++) {
if (isPal(s, i, j)) {
bestL = i;
bestLen = j - i + 1;
}
}
}
return s.substring(bestL, bestL + bestLen);
}
private boolean isPal(String s, int l, int r) {
while (l < r) {
if (s.charAt(l++) != s.charAt(r--)) return false;
}
return true;
}
}class Solution:
def longestPalindrome(self, s: str) -> str:
n = len(s)
best_l, best_len = 0, 1
def is_pal(l: int, r: int) -> bool:
while l < r:
if s[l] != s[r]:
return False
l += 1
r -= 1
return True
for i in range(n):
for j in range(i + best_len, n):
if is_pal(i, j):
best_l, best_len = i, j - i + 1
return s[best_l:best_l + best_len]class Solution {
bool isPal(const string& s, int l, int r) {
while (l < r) {
if (s[l++] != s[r--]) return false;
}
return true;
}
public:
string longestPalindrome(string s) {
int n = s.size(), bestL = 0, bestLen = 1;
for (int i = 0; i < n; i++) {
for (int j = i + bestLen; j < n; j++) {
if (isPal(s, i, j)) {
bestL = i;
bestLen = j - i + 1;
}
}
}
return s.substr(bestL, bestLen);
}
};function longestPalindrome(s) {
const n = s.length;
let bestL = 0, bestLen = 1;
const isPal = (l, r) => {
while (l < r) {
if (s[l++] !== s[r--]) return false;
}
return true;
};
for (let i = 0; i < n; i++) {
for (let j = i + bestLen; j < n; j++) {
if (isPal(i, j)) {
bestL = i;
bestLen = j - i + 1;
}
}
}
return s.substring(bestL, bestL + bestLen);
}2Better (DP table)
O(n²)Each of the n² cells is filled in O(1).O(n²)The n × n boolean table.s[i..j] is a palindrome exactly when its end characters match and the inside s[i+1..j-1] is a palindrome (or has length 0 or 1). Fill a boolean table by increasing length so the inside is always known first.
- dp[i][j] = s[i] == s[j] && (j - i < 2 || dp[i + 1][j - 1]).
- Process i from n - 1 down to 0 and j from i up to n - 1, so dp[i + 1][j - 1] is ready.
- Whenever dp[i][j] is true and longer than the best, record it.
class Solution {
public String longestPalindrome(String s) {
int n = s.length(), bestL = 0, bestLen = 1;
boolean[][] dp = new boolean[n][n];
for (int i = n - 1; i >= 0; i--) {
for (int j = i; j < n; j++) {
dp[i][j] = s.charAt(i) == s.charAt(j) && (j - i < 2 || dp[i + 1][j - 1]);
if (dp[i][j] && j - i + 1 > bestLen) {
bestL = i;
bestLen = j - i + 1;
}
}
}
return s.substring(bestL, bestL + bestLen);
}
}class Solution:
def longestPalindrome(self, s: str) -> str:
n = len(s)
best_l, best_len = 0, 1
dp = [[False] * n for _ in range(n)]
for i in range(n - 1, -1, -1):
for j in range(i, n):
dp[i][j] = s[i] == s[j] and (j - i < 2 or dp[i + 1][j - 1])
if dp[i][j] and j - i + 1 > best_len:
best_l, best_len = i, j - i + 1
return s[best_l:best_l + best_len]class Solution {
public:
string longestPalindrome(string s) {
int n = s.size(), bestL = 0, bestLen = 1;
vector<vector<bool>> dp(n, vector<bool>(n, false));
for (int i = n - 1; i >= 0; i--) {
for (int j = i; j < n; j++) {
dp[i][j] = s[i] == s[j] && (j - i < 2 || dp[i + 1][j - 1]);
if (dp[i][j] && j - i + 1 > bestLen) {
bestL = i;
bestLen = j - i + 1;
}
}
}
return s.substr(bestL, bestLen);
}
};function longestPalindrome(s) {
const n = s.length;
let bestL = 0, bestLen = 1;
const dp = Array.from({ length: n }, () => new Array(n).fill(false));
for (let i = n - 1; i >= 0; i--) {
for (let j = i; j < n; j++) {
dp[i][j] = s[i] === s[j] && (j - i < 2 || dp[i + 1][j - 1]);
if (dp[i][j] && j - i + 1 > bestLen) {
bestL = i;
bestLen = j - i + 1;
}
}
}
return s.substring(bestL, bestL + bestLen);
}3Optimal (expand around each center)
O(n²)2n - 1 centers, and each expansion moves at most n steps.O(1)Only a few indices.Every palindrome mirrors around a center, which is either one character (odd length) or the gap between two characters (even length). For each of the 2n - 1 centers, push two pointers outward while the characters match. The widest expansion seen is the answer, and no table is needed.
- For each i, expand from (i, i) for odd lengths and from (i, i + 1) for even lengths.
- expand(l, r): while l >= 0, r < n and s[l] == s[r], move l left and r right; the palindrome is s[l + 1 .. r - 1].
- Keep the start and length of the longest one.
class Solution {
private int bestL = 0, bestLen = 0;
public String longestPalindrome(String s) {
bestL = 0;
bestLen = 0;
for (int i = 0; i < s.length(); i++) {
expand(s, i, i);
expand(s, i, i + 1);
}
return s.substring(bestL, bestL + bestLen);
}
private void expand(String s, int l, int r) {
while (l >= 0 && r < s.length() && s.charAt(l) == s.charAt(r)) {
l--;
r++;
}
if (r - l - 1 > bestLen) {
bestL = l + 1;
bestLen = r - l - 1;
}
}
}class Solution:
def longestPalindrome(self, s: str) -> str:
n = len(s)
best_l, best_len = 0, 0
for i in range(n):
for l, r in ((i, i), (i, i + 1)):
while l >= 0 and r < n and s[l] == s[r]:
l -= 1
r += 1
if r - l - 1 > best_len:
best_l, best_len = l + 1, r - l - 1
return s[best_l:best_l + best_len]class Solution {
int bestL = 0, bestLen = 0;
void expand(const string& s, int l, int r) {
while (l >= 0 && r < (int)s.size() && s[l] == s[r]) {
l--;
r++;
}
if (r - l - 1 > bestLen) {
bestL = l + 1;
bestLen = r - l - 1;
}
}
public:
string longestPalindrome(string s) {
bestL = 0;
bestLen = 0;
for (int i = 0; i < (int)s.size(); i++) {
expand(s, i, i);
expand(s, i, i + 1);
}
return s.substr(bestL, bestLen);
}
};function longestPalindrome(s) {
const n = s.length;
let bestL = 0, bestLen = 0;
const expand = (l, r) => {
while (l >= 0 && r < n && s[l] === s[r]) {
l--;
r++;
}
if (r - l - 1 > bestLen) {
bestL = l + 1;
bestLen = r - l - 1;
}
};
for (let i = 0; i < n; i++) {
expand(i, i);
expand(i, i + 1);
}
return s.substring(bestL, bestL + bestLen);
}Edge cases to test
- A single character
- All characters equal, like "aaaa": the whole string
- No repeated neighbors: the answer has length 1
- The longest palindrome sits at the very start or very end
- Even-length palindromes, which have no middle character
Hints
Hint 1
Checking every substring works but costs O(n³). Can you grow palindromes instead of testing them?
Hint 2
Every palindrome has a center. There are only 2n - 1 centers: each character, and each gap between two neighbors.
Hint 3
From each center, expand outward while both ends match, and remember the widest expansion.
FAQ
What is the best time complexity for Longest Palindromic Substring?
Optimal (expand around each center) runs in O(n²) time and O(1) extra space. 2n - 1 centers, and each expansion moves at most n steps.
Which pattern does Longest Palindromic Substring use?
It is a dynamic programming problem that uses the strings pattern. Other problems with the same pattern: Edit Distance, Longest Common Subsequence, Longest Palindromic Subsequence.
Is there a brute force solution for Longest Palindromic Substring?
Yes. Brute force (check every substring) takes O(n³) time and O(1) space. Try every pair of start and end indices, check whether that block is a palindrome with two pointers, and keep the longest one found.
Which edge cases should I test for Longest Palindromic Substring?
A single character; All characters equal, like "aaaa": the whole string; No repeated neighbors: the answer has length 1; The longest palindrome sits at the very start or very end; Even-length palindromes, which have no middle character.