Skip to content

Longest Palindromic Substring

Find the longest substring that reads the same both ways by growing palindromes out from each center.

Medium2D Dynamic Programming
Solve on LeetCode

The problem

You get a string s of letters and digits. Return its longest substring that is a palindrome, meaning it reads the same forwards and backwards. If several substrings tie for the longest, return any one of them.

Input s = "xracecarz"

Output "racecar"

racecar reads the same both ways, and adding the x or the z would break it.

Input s = "abbac"

Output "abba"

An even-length palindrome: its center sits between the two b's.

Key constraint: The string has at most 1,000 characters, so O(n^2) work is fine, but checking every substring in O(n^3) is not.

How to spot the pattern

  • You want the longest substring with a mirror property.
  • A palindrome stays a palindrome when you peel off its two end letters.

The idea

Think of the DP state pal(i, j): s[i..j] is a palindrome when s[i] == s[j] and pal(i + 1, j - 1) is true. So every palindrome grows out of a smaller one with the same center, one letter on each side. Instead of filling an n x n table, start at each of the 2n - 1 centers (on a letter or between two letters) and expand while the two ends match; each step is that transition, and it needs only O(1) memory.

Brute force: Check each of the O(n^2) substrings for being a palindrome, which takes O(n^3) time.

Step by step

  1. 1For each index, try two centers: the letter itself for odd lengths and the gap after it for even lengths.
  2. 2Set lo and hi to the center and move them outward while both are inside the string and s[lo] == s[hi].
  3. 3When the loop stops, the palindrome is s[lo + 1..hi - 1], with length hi - lo - 1.
  4. 4If that is longer than the best so far, remember its start and length.
  5. 5Return the best substring.

See the pattern move

The 2d dynamic programming pattern on a small example. Step through it, or press play.

Code

class Solution:
    def longestPalindrome(self, s: str) -> str:
        n = len(s)
        best_start, best_len = 0, 1
        for center in range(n):
            # odd lengths sit on one letter, even lengths between two letters
            for lo, hi in ((center, center), (center, center + 1)):
                # s[lo..hi] is a palindrome when s[lo] == s[hi] and s[lo + 1..hi - 1] is one
                while lo >= 0 and hi < n and s[lo] == s[hi]:
                    lo -= 1
                    hi += 1
                # the loop stopped one step past each end
                if hi - lo - 1 > best_len:
                    best_start, best_len = lo + 1, hi - lo - 1
        return s[best_start:best_start + best_len]

Complexity

Time

O(n^2)

Space

O(1)

There are 2n - 1 centers and each expands at most n / 2 steps; only a few indexes are kept.

Watch out for

  • Trying only odd-length centers, which misses answers like abba.
  • Getting the bounds wrong after the loop: it stops one step past each end, so the palindrome starts at lo + 1.

Follow-up questions

Can you write it as a table DP?

Yes: fill pal[i][j] for i from n - 1 down to 0 and j from i up, reading pal[i + 1][j - 1]. The time is the same O(n^2), but it needs O(n^2) memory.

Can it be done in O(n)?

Manacher's algorithm reuses the mirror image of palindromes it has already found to skip repeated expansions, which gives O(n) time.

In Hinglish

Har palindrome ka ek center hota hai, ek letter ya do letters ke beech. Har center se dono taraf failao jab tak letters match karein, aur sabse lamba yaad rakho.

Related problems