15% off all plans & roadmaps Use code
See plansLongest Palindromic Substring
- LeetCode 5
- Medium
- Two Pointers
- Expanding From Center (Palindromes)
Updated
TL;DR: Find the longest substring that reads the same forwards and backwards. Expand outward from each of the 2n-1 possible centers and keep the longest match, which runs in O(n^2) time and O(1) space.
Problem
Given a string s, return the longest palindromic substring in s. A palindrome reads the same forwards and backwards. If several answers have the same length, any one of them is accepted.
Example 1
Input: s = "babad" Output: "bab" Explanation: "aba" is also a valid answer.
Example 2
Input: s = "cbbd" Output: "bb"
Constraints
1 <= s.length <= 1000sconsists of only digits and English letters.
Constraints that matter
s.length <= 1000means an O(n^2) solution does about 10^6 steps, which is fast. An O(n^3) solution does up to about 10^8 character comparisons, which is slow in interpreted languages.s.length >= 1means the answer always exists, because any single character is a palindrome. You never return an empty string.- Only digits and English letters appear, so every character is one byte and slicing by index is safe in all six languages.
- Any longest palindrome is accepted on ties, so you may keep the first one found and ignore later palindromes of equal length.
Hints
Hint 1
This is an expand-from-center problem, a form of two pointers.
Hint 2
List every substring, test each one for being a palindrome, and keep the longest.
Solution
Intuition
This is an expand-from-center problem, a form of two pointers. A palindrome mirrors around its middle. If you know the middle, you can check the palindrome by walking one pointer left and one pointer right while the characters match.
Picture two people starting at the middle of a line of paired lockers and walking outward together. The middle is the center, each matching pair of lockers is one layer of the palindrome, and the first mismatch is where they stop.
The brute force fixes the two ends of a substring first and then checks the inside. That wastes work, because the substrings s[3..12] and s[4..11] share almost all their characters and the check starts over each time. Fixing the center first turns the check into a growth process. A palindrome of length 10 is a palindrome of length 8 plus one matching pair on the outside.
There are two kinds of center. An odd palindrome like aba has a character in the middle. An even palindrome like abba has a gap between two equal characters. A string of length n has n character centers and n-1 gap centers, so 2n-1 centers in total.
Every palindromic substring has exactly one center, so trying all 2n-1 centers and expanding each as far as it goes cannot miss the answer. Each expansion costs at most n steps. That gives O(n^2) time without any extra table.
Worked example
Input: s = "forgeeksskeegfor" Output: "geeksskeeg" Explanation: The string has 16 characters. The two middle characters at indices 7 and 8 are both 's', and the match keeps growing through k, e, e, g. It stops when 'r' at index 2 meets 'f' at index 13. That leaves indices 3 to 12, which spell "geeksskeeg", a palindrome of length 10.
Approach 1: Brute force
List every substring, test each one for being a palindrome, and keep the longest. A substring is defined by its start i and end j. The test compares the first and last characters, then the second and second to last, and so on.
This is easy to get right and it is the baseline an interviewer expects you to state first. It is also slow, because each of the roughly n^2 / 2 substrings costs up to n / 2 comparisons.
Steps
- Set
start = 0andbestLen = 1, since any single character is a palindrome. - Loop
iover every start index from 0 to n-1. - Loop
jover every end index fromito n-1. - If the length
j - i + 1beatsbestLen, tests[i..j]with two pointers moving inward. - If the test passes, store
start = iandbestLen = j - i + 1. - Return
s[start .. start + bestLen).
Dry run
Run on the example forgeeksskeegfor. The loops visit all 136 substrings. Each candidate that is longer than the current best gets a two-pointer test.
i = 0:fo,forand longer substrings starting at 'f' fail on the first or second comparison. The best stays at length 1.i = 4:eepasses, sobestLen = 2andstart = 4.i = 3:geeksskeeg(j = 12) passes after five matching pairs, sobestLen = 10andstart = 3.- Every later candidate has length at most 10, so none beats the best. Starts at
i = 4and beyond cannot reach length 11 within a 16-character string.
The loop ends with start = 3 and bestLen = 10, so the result is geeksskeeg.
Complexity
| Time | O(n^3) |
|---|---|
| Space | O(1) |
Let n be the length of s. The two loops produce n * (n + 1) / 2 substrings, which is O(n^2). Each palindrome test runs at most half the substring length, which is O(n). Multiplying gives O(n^3). The code stores only a few integers and compares in place, so extra space is O(1).
PythonTested in our runner
from typing import List, Optional
class Solution:
def longestPalindrome(self, s: str) -> str:
n = len(s)
best = s[0]
for i in range(n):
for j in range(i, n):
sub = s[i:j + 1]
# compare against the reversed copy to test for a palindrome
if len(sub) > len(best) and sub == sub[::-1]:
best = sub
return best
JavaTested in our runner
import java.util.*;
class Solution {
public String longestPalindrome(String s) {
int n = s.length();
int start = 0, bestLen = 1;
for (int i = 0; i < n; i++) {
for (int j = i; j < n; j++) {
int len = j - i + 1;
if (len > bestLen && isPalindrome(s, i, j)) {
start = i;
bestLen = len;
}
}
}
return s.substring(start, start + bestLen);
}
private boolean isPalindrome(String s, int l, int r) {
while (l < r) {
if (s.charAt(l) != s.charAt(r)) return false;
l++;
r--;
}
return true;
}
}
C++Tested in our runner
#include <string>
using namespace std;
class Solution {
public:
string longestPalindrome(string s) {
int n = s.size();
int start = 0, bestLen = 1;
for (int i = 0; i < n; i++) {
for (int j = i; j < n; j++) {
int len = j - i + 1;
if (len > bestLen && isPalindrome(s, i, j)) {
start = i;
bestLen = len;
}
}
}
return s.substr(start, bestLen);
}
private:
bool isPalindrome(const string& s, int l, int r) {
while (l < r) {
if (s[l] != s[r]) return false;
l++;
r--;
}
return true;
}
};
JavaScriptTested in our runner
/**
* @param {string} s
* @return {string}
*/
var longestPalindrome = function(s) {
const n = s.length;
let start = 0, bestLen = 1;
for (let i = 0; i < n; i++) {
for (let j = i; j < n; j++) {
const len = j - i + 1;
if (len > bestLen && isPalindrome(s, i, j)) {
start = i;
bestLen = len;
}
}
}
return s.substring(start, start + bestLen);
};
function isPalindrome(s, l, r) {
while (l < r) {
if (s[l] !== s[r]) return false;
l++;
r--;
}
return true;
}
GoTested in our runner
func longestPalindrome(s string) string {
n := len(s)
start, bestLen := 0, 1
for i := 0; i < n; i++ {
for j := i; j < n; j++ {
length := j - i + 1
if length > bestLen && isPalindromeRange(s, i, j) {
start = i
bestLen = length
}
}
}
return s[start : start+bestLen]
}
func isPalindromeRange(s string, l, r int) bool {
for l < r {
if s[l] != s[r] {
return false
}
l++
r--
}
return true
}
C#Tested in our runner
public class Solution {
public string longestPalindrome(string s) {
int n = s.Length;
int start = 0, bestLen = 1;
for (int i = 0; i < n; i++) {
for (int j = i; j < n; j++) {
int len = j - i + 1;
if (len > bestLen && IsPalindrome(s, i, j)) {
start = i;
bestLen = len;
}
}
}
return s.Substring(start, bestLen);
}
private bool IsPalindrome(string s, int l, int r) {
while (l < r) {
if (s[l] != s[r]) return false;
l++;
r--;
}
return true;
}
}
Approach 2: Dynamic programming table
What's slow: the brute force re-checks the inside of every substring from scratch. The substring s[3..12] contains s[4..11], which contains s[5..10], and each test walks all of those pairs again.
The insight that fixes it: a substring s[i..j] is a palindrome exactly when s[i] == s[j] and the inner substring s[i+1..j-1] is a palindrome. Store that answer in a table dp[i][j] so each substring is decided in O(1) from a smaller one. Substrings of length 1 are always palindromes. Substrings of length 2 and 3 need only s[i] == s[j], because their inner part is empty or a single character.
Steps
- Create an n by n boolean table
dp, all false. - Loop
ifrom n-1 down to 0, so rowi+1is complete before rowineeds it. - Loop
jfromito n-1. - Mark
dp[i][j]true whens[i] == s[j]and eitherj - i < 3ordp[i+1][j-1]is true. - When you mark a cell true and
j - i + 1beatsbestLen, recordstart = iandbestLen. - Return
s[start .. start + bestLen).
Dry run
Run on forgeeksskeegfor (n = 16). Rows are filled from i = 15 up to i = 0.
- Every
dp[i][i]is true, sobestLen = 1. The first row that improves it isi = 10:dp[10][11]is true becauses[10] == s[11] == 'e'andj - i = 1 < 3. SobestLen = 2,start = 10. - Row
i = 7:dp[7][8]is true ('s','s'). Thendp[6][9]('k','k') needsdp[7][8], which is true. Thendp[5][10]needsdp[6][9], thendp[4][11]needsdp[5][10]. - Row
i = 3:dp[3][12]('g','g') needsdp[4][11], which is true. That setsbestLen = 10,start = 3. - Row
i = 2:dp[2][13]fails because 'r' is not 'f'. No later cell reaches 11.
The answer is s[3..12] = geeksskeeg.
Complexity
| Time | O(n^2) |
|---|---|
| Space | O(n^2) |
Let n be the length of s. The table has n * n cells and each cell is computed with one comparison and one table lookup, so time is O(n^2). The table itself holds n * n booleans, so space is O(n^2). For n = 1000 that is one million cells, which fits comfortably.
PythonTested in our runner
from typing import List, Optional
class Solution:
def longestPalindrome(self, s: str) -> str:
n = len(s)
dp = [[False] * n for _ in range(n)]
start, best = 0, 1
for i in range(n - 1, -1, -1):
for j in range(i, n):
# inner part is empty or one char when j - i < 3
if s[i] == s[j] and (j - i < 3 or dp[i + 1][j - 1]):
dp[i][j] = True
# >= so ties prefer the earliest start (i decreases)
if j - i + 1 >= best:
best = j - i + 1
start = i
return s[start:start + best]
JavaTested in our runner
class Solution {
public String longestPalindrome(String s) {
int n = s.length();
boolean[][] dp = new boolean[n][n];
int start = 0, best = 1;
// i runs downward, so on equal length the smaller start overwrites (>=) and the earliest wins
for (int i = n - 1; i >= 0; i--) {
for (int j = i; j < n; j++) {
if (s.charAt(i) == s.charAt(j) && (j - i < 3 || dp[i + 1][j - 1])) {
dp[i][j] = true;
if (j - i + 1 >= best) {
best = j - i + 1;
start = i;
}
}
}
}
return s.substring(start, start + best);
}
}C++Tested in our runner
#include <string>
#include <vector>
using namespace std;
class Solution {
public:
string longestPalindrome(string s) {
int n = s.size();
vector<vector<bool>> dp(n, vector<bool>(n, false));
int start = 0, best = 1;
for (int i = n - 1; i >= 0; i--) {
for (int j = i; j < n; j++) {
if (s[i] == s[j] && (j - i < 3 || dp[i + 1][j - 1])) {
dp[i][j] = true;
// >= so that among equal lengths the leftmost start wins (i decreases)
if (j - i + 1 >= best) {
best = j - i + 1;
start = i;
}
}
}
}
return s.substr(start, best);
}
};
JavaScriptTested in our runner
/**
* @param {string} s
* @return {string}
*/
var longestPalindrome = function(s) {
const n = s.length;
const dp = Array.from({ length: n }, () => new Array(n).fill(false));
let start = 0, best = 1;
for (let i = n - 1; i >= 0; i--) {
for (let j = i; j < n; j++) {
if (s[i] === s[j] && (j - i < 3 || dp[i + 1][j - 1])) {
dp[i][j] = true;
// >= prefers the leftmost start on ties, since i decreases
if (j - i + 1 >= best) {
best = j - i + 1;
start = i;
}
}
}
}
return s.substring(start, start + best);
};
GoTested in our runner
func longestPalindrome(s string) string {
n := len(s)
if n == 0 {
return ""
}
// dp[i][j] is true when s[i..j] is a palindrome
dp := make([][]bool, n)
for i := range dp {
dp[i] = make([]bool, n)
}
start, best := 0, 1
for i := n - 1; i >= 0; i-- {
for j := i; j < n; j++ {
if s[i] == s[j] && (j-i < 3 || dp[i+1][j-1]) {
dp[i][j] = true
l := j - i + 1
// prefer longer; on ties prefer the earlier start
if l > best || (l == best && i < start) {
best = l
start = i
}
}
}
}
return s[start : start+best]
}C#Tested in our runner
public class Solution {
public string longestPalindrome(string s) {
int n = s.Length;
bool[,] dp = new bool[n, n];
int start = 0, best = 1;
for (int i = n - 1; i >= 0; i--) {
for (int j = i; j < n; j++) {
if (s[i] == s[j] && (j - i < 3 || dp[i + 1, j - 1])) {
dp[i, j] = true;
// >= because i descends, so ties move to the earlier start
if (j - i + 1 >= best) {
best = j - i + 1;
start = i;
}
}
}
}
return s.Substring(start, best);
}
}
Solution pattern
Expanding From Center (Palindromes)
Part of Two Pointers
Approach 3: Expand around each centerOptimalExpanding From Center (Palindromes)
What's slow: the DP table stores n * n answers, but most of them are false, and you only ever read the cell diagonally inside the current one. The memory is far larger than the information you need.
The insight that fixes it: a palindrome grows from its center one matching pair at a time, so you do not need a table at all. For each of the 2n-1 centers, put a left pointer and a right pointer on it and move them apart while s[left] == s[right]. When the loop stops, the palindrome is the range strictly between the pointers, with length right - left - 1. Keep the best start and length seen so far.
Why it is correct. Any palindrome around a given center is built from nested pairs of equal characters, so it must contain every inner pair. The first mismatch therefore caps the palindrome at that center, and no longer one can exist there. Since every palindromic substring has exactly one center, checking all centers and keeping the best length finds the global maximum.
Steps
- Set
start = 0andbestLen = 1. - For each index
i, runexpand(i, i)for the odd palindrome centered on a character. - For the same
i, runexpand(i, i + 1)for the even palindrome centered on the gap afteri. - Inside
expand, loop whileleft >= 0,right < nands[left] == s[right], movingleftdown andrightup. - Return
right - left - 1fromexpand, since both pointers have stepped one place past the palindrome. - Take the larger of the two lengths. If it beats
bestLen, setbestLenandstart = i - (len - 1) / 2using integer division. - Return
s[start .. start + bestLen).
Dry run
Run on forgeeksskeegfor. Each row shows the lengths found for the odd center i and the even center between i and i + 1.
| i | char | odd length | even length | best length | start |
|---|---|---|---|---|---|
| 0 | f | 1 | 0 | 1 | 0 |
| 1 | o | 1 | 0 | 1 | 0 |
| 2 | r | 1 | 0 | 1 | 0 |
| 3 | g | 1 | 0 | 1 | 0 |
| 4 | e | 1 | 2 (e,e at 4,5) | 2 | 4 |
| 5 | e | 1 | 0 | 2 | 4 |
| 6 | k | 1 | 0 | 2 | 4 |
| 7 | s | 1 | 10 (s,k,e,e,g pairs) | 10 | 3 |
| 8 | s | 1 | 0 | 10 | 3 |
| 9 | k | 1 | 0 | 10 | 3 |
| 10 | e | 1 | 2 | 10 | 3 |
| 11 | e | 1 | 0 | 10 | 3 |
| 12 | g | 1 | 0 | 10 | 3 |
| 13 to 15 | f, o, r | 1 | 0 | 10 | 3 |
At i = 7 the even expansion starts with left = 7, right = 8. It matches five pairs: (7,8), (6,9), (5,10), (4,11), (3,12). Then it stops at left = 2, right = 13 because 'r' is not 'f'.
The length is 13 - 2 - 1 = 10, and start = 7 - (10 - 1) / 2 = 7 - 4 = 3. The result is s[3..12] = geeksskeeg.
Complexity
| Time | O(n^2) |
|---|---|
| Space | O(1) |
Let n be the length of s. There are 2n-1 centers, and each expansion moves the pointers at most n / 2 steps outward before hitting a boundary. Total work is at most (2n-1) * n / 2, which is O(n^2). The worst case is a string like aaaa...a, where every expansion runs to the boundary. Only a handful of integers are stored, so extra space is O(1).
PythonTested in our runner
from typing import List, Optional
class Solution:
def longestPalindrome(self, s: str) -> str:
start, best = 0, 1
for i in range(len(s)):
odd = self.expand(s, i, i)
even = self.expand(s, i, i + 1)
length = max(odd, even)
if length > best:
best = length
start = i - (length - 1) // 2
return s[start:start + best]
def expand(self, s: str, left: int, right: int) -> int:
while left >= 0 and right < len(s) and s[left] == s[right]:
left -= 1
right += 1
# both pointers are one step outside the palindrome
return right - left - 1
JavaTested in our runner
import java.util.*;
class Solution {
public String longestPalindrome(String s) {
int start = 0, best = 1;
for (int i = 0; i < s.length(); i++) {
int odd = expand(s, i, i);
int even = expand(s, i, i + 1);
int len = Math.max(odd, even);
if (len > best) {
best = len;
start = i - (len - 1) / 2;
}
}
return s.substring(start, start + best);
}
private int expand(String s, int left, int right) {
while (left >= 0 && right < s.length() && s.charAt(left) == s.charAt(right)) {
left--;
right++;
}
return right - left - 1;
}
}
C++Tested in our runner
#include <string>
#include <algorithm>
using namespace std;
class Solution {
public:
string longestPalindrome(string s) {
int start = 0, best = 1;
for (int i = 0; i < (int)s.size(); i++) {
int odd = expand(s, i, i);
int even = expand(s, i, i + 1);
int len = max(odd, even);
if (len > best) {
best = len;
start = i - (len - 1) / 2;
}
}
return s.substr(start, best);
}
private:
int expand(const string& s, int left, int right) {
while (left >= 0 && right < (int)s.size() && s[left] == s[right]) {
left--;
right++;
}
return right - left - 1;
}
};
JavaScriptTested in our runner
/**
* @param {string} s
* @return {string}
*/
var longestPalindrome = function(s) {
let start = 0, best = 1;
for (let i = 0; i < s.length; i++) {
const odd = expand(s, i, i);
const even = expand(s, i, i + 1);
const len = Math.max(odd, even);
if (len > best) {
best = len;
start = i - Math.floor((len - 1) / 2);
}
}
return s.substring(start, start + best);
};
function expand(s, left, right) {
while (left >= 0 && right < s.length && s[left] === s[right]) {
left--;
right++;
}
return right - left - 1;
}
GoTested in our runner
func longestPalindrome(s string) string {
start, best := 0, 1
for i := 0; i < len(s); i++ {
odd := expandCenter(s, i, i)
even := expandCenter(s, i, i+1)
length := odd
if even > length {
length = even
}
if length > best {
best = length
start = i - (length-1)/2
}
}
return s[start : start+best]
}
func expandCenter(s string, left, right int) int {
for left >= 0 && right < len(s) && s[left] == s[right] {
left--
right++
}
return right - left - 1
}
C#Tested in our runner
public class Solution {
public string longestPalindrome(string s) {
int start = 0, best = 1;
for (int i = 0; i < s.Length; i++) {
int odd = Expand(s, i, i);
int even = Expand(s, i, i + 1);
int len = Math.Max(odd, even);
if (len > best) {
best = len;
start = i - (len - 1) / 2;
}
}
return s.Substring(start, best);
}
private int Expand(string s, int left, int right) {
while (left >= 0 && right < s.Length && s[left] == s[right]) {
left--;
right++;
}
return right - left - 1;
}
}
Common mistakes
- Only calling
expand(i, i). This finds odd palindromes and missesbbandabba. Add the second callexpand(i, i + 1)for everyi. - Returning
right - left + 1fromexpand. The loop exits after the pointers have stepped one place past the palindrome on each side. The correct length isright - left - 1. - Computing the start as
i - len / 2. For an even length this is off by one. Usei - (len - 1) / 2with integer division, which works for both odd and even lengths. - Putting
s[left] == s[right]before the bounds checks in thewhilecondition. You read index -1 or n and crash in Java, C# and Go, or compare against undefined in JavaScript. Checkleft >= 0andright < nfirst. - Setting
bestLen = 0and startingstartat 0 for a one-character string. If the update uses>, the answer can come back empty. Start withbestLen = 1, or make sure the first expansion always updates. - In the DP, looping
iupward from 0. Celldp[i][j]readsdp[i+1][j-1], which is not filled yet. Loopifrom n-1 down to 0, or iterate by substring length.
Edge cases
s = "a": the answer is"a". Both expansions run, but only the odd one succeeds, andbestLen = 1is already correct.s = "bb": the answer is"bb". Only the even center ati = 0finds it, so this tests that you handle even palindromes.s = "ab": no pair matches, so the answer is any single character. Returning"a"is correct.s = "aaaa...a"with 1000 characters: the whole string is a palindrome and every expansion runs to the boundary. This is the worst case for time, and the answer is the full string.s = "cbbd": the answer is"bb". The even center between indices 1 and 2 matches, then 'c' against 'd' stops it.s = "babad": both"bab"and"aba"are valid. Using a strict>for updates returns"bab", the first one found.
Follow-ups interviewers ask
- Can you do better than O(n^2) time?
- Yes. Manacher's algorithm finds the longest palindrome around every center in O(n) total time. It reuses the radii of palindromes already found. Inside a big palindrome, the radius at a mirrored position gives a starting guess, so the pointers never re-scan characters they have already confirmed. You insert a separator between characters so odd and even centers become one case. It is rarely required in an interview, but you should be able to name it and sketch the mirror idea.
- What if you must count all palindromic substrings instead of finding the longest?
- Use the same 2n-1 centers. Each successful expansion step from a center is one new palindrome, so you add one to a counter every time the pointers match. The total time is still O(n^2) and the space is O(1). This is the problem Palindromic Substrings, LeetCode 647.
- What if the string is too large to fit in memory?
- Expansion needs random access around the current center, so you cannot stream it one pass in the plain form. You can process it in overlapping windows. Each window must be at least as long as twice the longest palindrome you expect, so a palindrome crossing a window boundary still lands fully inside the next window. Manacher's algorithm keeps only the current radius array for a window, which makes it the natural choice for that setting.
Longest Palindromic Substring FAQ
What is the time complexity of Longest Palindromic Substring?
The expand-around-center solution is O(n^2) time and O(1) space. There are 2n-1 centers and each expansion takes at most n / 2 steps. The brute force is O(n^3), the DP table is O(n^2) time and O(n^2) space, and Manacher's algorithm reaches O(n).
Why use expand from center for Longest Palindromic Substring?
A palindrome is defined by its center, and it grows by one matching pair at a time. Expanding from each center reuses the work already done for the smaller palindrome inside it. This gets the speed of the DP table without storing the table.
Can Longest Palindromic Substring be solved in O(1) extra space?
Yes, in O(n^2) time. Expand around center keeps only a few integers, plus the returned substring. The O(n) time Manacher's algorithm needs an array of radii, so it uses O(n) extra space.
Why does the expand function return right - left - 1?
The loop stops when the characters differ or a pointer leaves the string. At that moment left is one place before the palindrome and right is one place after it. The palindrome occupies indices left + 1 through right - 1, which is right - left - 1 characters.
What is the difference between a palindromic substring and a palindromic subsequence?
A substring must be contiguous. A subsequence can skip characters while keeping their order. This page solves the substring version, which is LeetCode 5. The subsequence version is a different problem and uses a DP over two indices.
How do I solve Longest Palindromic Substring in Python or Java?
The three approaches above work in both languages with the same structure. In Python, return s[start:start + best]. In Java, return s.substring(start, start + best). Both languages use half-open ranges, so no extra adjustment is needed.
Asked at
See which companies ask this — Pro
Related problems
- Palindromic Substrings · same technique: Expanding From Center (Palindromes)
- Trapping Rain Water · next harder, same pattern
- Sort Colors · same pattern: Two Pointers
- 3Sum · same pattern: Two Pointers
- Container With Most Water · same pattern: Two Pointers
- Remove Nth Node From End of List · same pattern: Two Pointers
- Find the Duplicate Number · same pattern: Two Pointers
- Reverse Integer · same pattern: Two Pointers
- Two Sum II - Input Array Is Sorted · same pattern: Two Pointers
- 4Sum · same pattern: Two Pointers