Longest Palindromic Substring
Medium
Topics
A palindrome reads identically from left to right and from right to left. Given a string s, find the longest contiguous piece of it that is a palindrome and return that piece.
Several different pieces can share the maximum length. When that happens, return the one that begins at the smallest index of s, so every input has exactly one correct answer.
Example 1
aba.Input: s = "xabay" Output: "aba" Explanation: No piece of length 4 or 5 mirrors itself, and "aba" is the only length-3 one.
Example 2
Input: s = "pqqr" Output: "qq"
Example 3
Input: s = "mn" Output: "m" Explanation: "m" and "n" are both length 1; "m" starts first.
Constraints
- 1 <= s.length <= 1000
- s consists of lowercase English letters and digits.
Editorial — intuition, approach, complexity and pitfalls
Intuition
Every palindrome mirrors around a centre. That centre is either a single character (odd length) or the gap between two neighbouring characters (even length), so a string of length n has only 2n - 1 possible centres.
From each centre, grow outwards while the characters on both sides match. The widest run you reach is the longest palindrome with that centre, and the answer is the best over all centres.
Approach
- Walk the centres from left to right: the character at
i, then the gap betweeniandi + 1. - For each centre, move two pointers outwards while they stay in bounds and point at equal characters.
- Record the span only if it is strictly longer than the best so far. Because centres are visited left to right, a tie never replaces the earlier start, which is what the statement asks for.
- Return the recorded slice.
Dry Run
s = "pqqr" -- expand around every centre
centre 0 odd "p" len 1
centre 1 odd "q" len 1
centre 1 even "qq" len 2 -> new best
centre 2 odd "q" len 1
centre 3 odd "r" len 1
answer "qq"
and on s = "xabay", where the answer is odd-length:
centre 2 odd "aba" len 3 -> new best
answer "aba"
Every index is tried as two centres: (i, i) for odd lengths and (i, i+1) for even.
Check only the odd ones and every even-length palindrome is invisible -- "pqqr"
then returns "p", and "abba" returns "a".
The update is strict `>`, which keeps the FIRST of several equal-length
palindromes. This input cannot show the difference; "abab" can, where both "aba"
and "bab" have length 3: `>` returns "aba" and `>=` returns "bab". Either is a
valid answer to the question as posed, but a judge comparing strings will only
accept one.
`expand` returns the start and length rather than the substring, so no string is
built until the end -- which is what keeps this O(1) extra space. A table-based
DP gets the same answer in O(n^2) memory for no gain.Complexity
- Time — O(n2): 2n - 1 centres, each expanding at most n/2 steps.
- Space — O(1): only the best start and length are stored.
Common Pitfalls
- Checking only odd centres misses answers like "qq".
- Updating on
>=instead of>returns the last of several equal-length palindromes rather than the first. Neither page example shows it;ababdoes, where>givesabaand>=givesbab. Both are valid answers to the question, but a judge comparing strings accepts only one. - A table-based DP also works but costs O(n2) memory for no gain here.
Full Solution — all languages
class Solution:
def longestPalindrome(self, s):
if not s:
return ""
best_start, best_len = 0, 1
def expand(lo, hi):
while lo >= 0 and hi < len(s) and s[lo] == s[hi]:
lo -= 1
hi += 1
return lo + 1, hi - lo - 1
for i in range(len(s)):
for lo, hi in ((i, i), (i, i + 1)):
start, length = expand(lo, hi)
if length > best_len:
best_start, best_len = start, length
return s[best_start:best_start + best_len]import java.util.*;
class Solution {
public String longestPalindrome(String s) {
if (s.isEmpty()) return "";
text = s;
int bestStart = 0, bestLen = 1;
for (int i = 0; i < s.length(); i++) {
int[] odd = expand(i, i);
if (odd[1] > bestLen) {
bestStart = odd[0];
bestLen = odd[1];
}
int[] even = expand(i, i + 1);
if (even[1] > bestLen) {
bestStart = even[0];
bestLen = even[1];
}
}
return s.substring(bestStart, bestStart + bestLen);
}
private String text;
private int[] expand(int lo, int hi) {
while (lo >= 0 && hi < text.length() && text.charAt(lo) == text.charAt(hi)) {
lo--;
hi++;
}
return new int[]{lo + 1, hi - lo - 1};
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: string longestPalindrome(string s) {
if (s.empty()) return "";
int bestStart = 0, bestLen = 1;
auto expand = [&](int lo, int hi) {
while (lo >= 0 && hi < (int)s.size() && s[lo] == s[hi]) {
lo--;
hi++;
}
return make_pair(lo + 1, hi - lo - 1);
};
for (int i = 0; i < (int)s.size(); i++) {
pair<int, int> odd = expand(i, i);
if (odd.second > bestLen) {
bestStart = odd.first;
bestLen = odd.second;
}
pair<int, int> even = expand(i, i + 1);
if (even.second > bestLen) {
bestStart = even.first;
bestLen = even.second;
}
}
return s.substr(bestStart, bestLen);
}
};/**
* @param {string} s
* @return {string}
*/ var longestPalindrome = function(s) {
if (!s.length) return "";
let bestStart = 0, bestLen = 1;
const expand = (lo, hi) => {
while (lo >= 0 && hi < s.length && s[lo] === s[hi]) {
lo--;
hi++;
}
return [lo + 1, hi - lo - 1];
};
for (let i = 0; i < s.length; i++) {
for (const pair of [[i, i], [i, i + 1]]) {
const got = expand(pair[0], pair[1]);
if (got[1] > bestLen) {
bestStart = got[0];
bestLen = got[1];
}
}
}
return s.substr(bestStart, bestLen);
};