Longest Palindromic Substring
Longest Palindromic Substring is LeetCode 5 (Medium). Given a string s, return its longest substring that reads the same forwards and backwards.
- A substring is a contiguous run of characters, so nothing in the middle can be skipped.
- If several palindromes share the longest length, any one of them is accepted.
s has at most 1,000 characters. Checking every substring on its own costs O(n³), so the target is O(n²).
- 1 <= s.length <= 1000
- s consist of only digits and English letters.
Intuition
A palindrome is mirrored around its middle. So instead of testing substrings one by one, pick a middle and grow the palindrome outward while the two new end characters match. The first mismatch ends that middle, because every wider window would still hold those two characters at mirror positions.
- Two kinds of middle: a character (odd length, like
aba) or the gap between two neighbours (even length, likeabba). A string of n characters has 2n − 1 of them. - Keep the widest: each middle reports the widest palindrome around it, and the answer is the widest report.
Every palindrome has exactly one middle, so trying all 2n − 1 middles cannot miss the longest one.
When a problem wants the best contiguous palindrome, grow candidates from their middles rather than checking each substring: a middle costs at most n / 2 comparisons and needs no table.
Approach
Before reading on, find the middle of abba and decide why starting only from single characters would never reach it. Aim for O(n²) time and O(1) extra space.
Two ways to solve it
Try all 2n − 1 middles and grow each one while the ends match.
- No table: two pointers per middle.
- Early stop: a mismatch ends the middle at once.
- Short code: one loop inside another.
The usual interview answer.
Mark every window s[i..j] that is a palindrome, using the answer for the window just inside it.
- Reusable: the table answers "is
s[i..j]a palindrome?" for any pair afterwards. - Watch out: n × n booleans, a million cells at n = 1,000.
Pick it when later steps need that table too.
Both run in O(n²) time; growing from middles wins because it needs no table. The steps, code and live demo follow that method, and the table version comes after the demo.
Try both middles at every index
For each index i, grow twice: once from l = r = i, with the middle on the character, and once from l = i, r = i + 1, with the middle in the gap after it. Together these cover all 2n − 1 middles, so every palindrome is reached from its own middle.
Grow while the ends match
While both pointers are inside the string and s[l] == s[r], move l one step left and r one step right. Each match means the window from l to r is a palindrome, because the part inside it matched on the step before.
Measure the window and keep the best
The loop stops one step too far on both sides, so the palindrome is s[l + 1 .. r − 1] and its length is r − l − 1. If that beats best, save its start and length. Slicing only once at the end avoids copying a string for every candidate.
Code in Python, C++ and Java
bab is a palindrome. The next step would leave the string, so this middle stops here. Width 3 beats the old best, so best becomes bab.aba is a palindrome.s[0:3] once at the end.bb is a palindrome.bb.s[1:3] once at the end.s[0:1] once at the end.Dynamic programming table
pal[i][j] is true when s[i..j] is a palindrome: its two end characters match, and the window inside it, pal[i + 1][j - 1], is a palindrome too. Windows of at most 3 characters only need the ends to match, since what is left inside is empty or one character. Running i from the end of the string down to 0 means the inside window is always filled before it is read.
Common pitfalls
Growing only from characters
for i in range(n):
l, r = i, ifor i in range(n):
for l, r in ((i, i), (i, i + 1)):An even-length palindrome has no middle character. For "cbbd" the character-only loop never compares the two bs with each other and returns "c" instead of "bb".
Reading the characters before checking the bounds
while s[l] == s[r] and l >= 0 and r < n:
while l >= 0 and r < n and s[l] == s[r]:
For "aa", the gap middle matches once and moves r to 2. The next test reads s[2], which crashes in Python and Java and reads past the string in C++. With the bounds first, the loop stops before the read.
Edge cases
"abc"Every middle stops at once, so best stays 1 and the answer is the first character, "a". A single character always counts as a palindrome.
"aaaa"Each middle grows until it hits an end of the string, so this is the slowest input, about n² / 4 comparisons. The middle gap reaches the whole string and returns "aaaa".
Complexity
start, best and the two pointers are stored; the returned substring is the output.Substring vs subsequence
The two problems share a name, but one keeps the characters together and the other may skip some.
| Problem | What counts | Answer for "bbbab" | Usual method |
|---|---|---|---|
| 5 Longest Palindromic Substring (this page) | a contiguous run of characters | "bbb", length 3 | grow from 2n − 1 middles, O(1) space |
| 516 Longest Palindromic Subsequence | characters kept in order, gaps allowed | "bbbb", length 4 | DP on dp[i][j] = best length inside s[i..j] |
Longest Palindromic Substring FAQ
Can it be found in O(n)?
Yes, with Manacher's algorithm. It puts a separator such as # between characters so every palindrome has odd length, then uses the mirror image inside the widest palindrome seen so far to skip comparisons it already knows the answer to. It is rarely asked for; with n at most 1,000, the O(n²) growth passes easily.
Does reversing the string and taking the longest common substring work?
Not on its own. For "abacdfgdcaba" the reverse is "abacdgfdcaba", and the longest common substring is "abacd", which is not a palindrome. It matches two separate copies of abacd, not one window and its mirror. Fixing that needs an extra position check, which ends up no simpler than growing from middles.