LeetCode #5 Medium

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²).

Constraints
  • 1 <= s.length <= 1000
  • s consist of only digits and English letters.
stringtwo pointersexpand around centre
Open on LeetCode ↗
02

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, like abba). 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.

How to spot this pattern

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.

03

Approach

Try it first

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.

1

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.

2

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.

3

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.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def longestPalindrome(self, s: str) -> str:
▶3 n = len(s)
▶4 start, best = 0, 1
▶5 for i in range(n):
▶6 for l, r in ((i, i), (i, i + 1)):
▶7 while l >= 0 and r < n and s[l] == s[r]:
▶8 l -= 1
▶9 r += 1
▶10 if r - l - 1 > best:
▶11 start, best = l + 1, r - l - 1
▶12 return s[start:start + best]
sb0a1b2a3d4widthbestb5 letters → 9 middles to try
s"babad"
best"b"length 1
Each dashed bar is a middle: the wide ones sit under a letter (odd-length palindromes), the narrow ones under the gap between two letters (even-length). best starts as the first letter, since one letter is always a palindrome.
sb0a1b2a3d4l = rwidth1bestbmiddle on b → width 1, edge
l, r0, 0
best"b"length 1
A single letter is a palindrome, so the middle at index 0 starts at width 1. The next step would leave the string, so this middle stops here. Width 1 does not beat the best of 1, so best stays.
sb0a1b2a3d4lrwidth10bestbgap after b: b and a differ → stop, width 0
l, r0, 1
best"b"length 1
Any wider window around this middle would hold b and a at mirror positions, so it cannot be a palindrome. This middle is done.
sb0a1b2a3d4l = rwidth101bestbmiddle on a → width 1
l, r1, 1
best"b"length 1
A single letter is a palindrome, so the middle at index 1 starts at width 1.
sb0a1b2a3d4lrwidth103bestbabb and b match → width 3, edge (new best)
l, r0, 2
best"bab"length 3
The two new end letters are equal and everything between them already matched, so 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.
sb0a1b2a3d4lrwidth1030bestbabgap after a: a and b differ → stop, width 0
l, r1, 2
best"bab"length 3
Any wider window around this middle would hold a and b at mirror positions, so it cannot be a palindrome. This middle is done.
sb0a1b2a3d4l = rwidth10301bestbabmiddle on b → width 1
l, r2, 2
best"bab"length 3
A single letter is a palindrome, so the middle at index 2 starts at width 1.
sb0a1b2a3d4lrwidth10303bestbaba and a match → width 3
l, r1, 3
best"bab"length 3
The two new end letters are equal and everything between them already matched, so aba is a palindrome.
sb0a1b2a3d4lrwidth10303bestbabb and d differ → stop, width 3
l, r0, 4
best"bab"length 3
Any wider window around this middle would hold b and d at mirror positions, so it cannot be a palindrome. This middle is done. Width 3 does not beat the best of 3, so best stays.
sb0a1b2a3d4lrwidth103030bestbabgap after b: b and a differ → stop, width 0
l, r2, 3
best"bab"length 3
Any wider window around this middle would hold b and a at mirror positions, so it cannot be a palindrome. This middle is done.
sb0a1b2a3d4l = rwidth1030301bestbabmiddle on a → width 1
l, r3, 3
best"bab"length 3
A single letter is a palindrome, so the middle at index 3 starts at width 1.
sb0a1b2a3d4lrwidth1030301bestbabb and d differ → stop, width 1
l, r2, 4
best"bab"length 3
Any wider window around this middle would hold b and d at mirror positions, so it cannot be a palindrome. This middle is done. Width 1 does not beat the best of 3, so best stays.
sb0a1b2a3d4lrwidth10303010bestbabgap after a: a and d differ → stop, width 0
l, r3, 4
best"bab"length 3
Any wider window around this middle would hold a and d at mirror positions, so it cannot be a palindrome. This middle is done.
sb0a1b2a3d4l = rwidth103030101bestbabmiddle on d → width 1, edge
l, r4, 4
best"bab"length 3
A single letter is a palindrome, so the middle at index 4 starts at width 1. The next step would leave the string, so this middle stops here. Width 1 does not beat the best of 3, so best stays.
sb0a1b2a3d4width103030101bestbabanswer: "bab"
start, best0, 3
answer"bab"
All 9 middles are done and the tallest bar is the answer. Every palindrome has exactly one middle, so none was missed. Slice s[0:3] once at the end.
05

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.

▶1class Solution:
▶2 def longestPalindrome(self, s: str) -> str:
▶3 n = len(s)
▶4 pal = [[False] * n for _ in range(n)]
▶5 start, best = 0, 1
▶6 for i in range(n - 1, -1, -1):
▶7 pal[i][i] = True
▶8 for j in range(i + 1, n):
▶9 if s[i] == s[j] and (j - i < 3 or pal[i + 1][j - 1]):
▶10 pal[i][j] = True
▶11 if j - i + 1 > best:
▶12 start, best = i, j - i + 1
▶13 return s[start:start + best]
06

Common pitfalls

Growing only from characters

✗ Wrong
for i in range(n):
    l, r = i, i
✓ Right
for 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

✗ Wrong
while s[l] == s[r] and l >= 0 and r < n:
✓ Right
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.

07

Edge cases

No palindrome longer than one character, e.g. "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.

Every character the same, e.g. "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".

08

Complexity

Time
O(n²)
Space
O(1)
There are 2n − 1 middles and each grows at most n / 2 steps. Only start, best and the two pointers are stored; the returned substring is the output.
09

Substring vs subsequence

The two problems share a name, but one keeps the characters together and the other may skip some.

ProblemWhat countsAnswer for "bbbab"Usual method
5 Longest Palindromic Substring (this page)a contiguous run of characters"bbb", length 3grow from 2n − 1 middles, O(1) space
516 Longest Palindromic Subsequencecharacters kept in order, gaps allowed"bbbb", length 4DP on dp[i][j] = best length inside s[i..j]
10

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.