Longest Palindromic Substring

Medium

Topics
StringTwo PointersDynamic Programming

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

x0a1b2a3y4aba
The braced run is the longest palindromic substring, aba.
Cells are the characters of the string; the small numbers underneath are indices.
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

p0q1q2r3qq
Input:  s = "pqqr"
Output: "qq"

Example 3

m0n1m
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

  1. Walk the centres from left to right: the character at i, then the gap between i and i + 1.
  2. For each centre, move two pointers outwards while they stay in bounds and point at equal characters.
  3. 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.
  4. 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; abab does, where > gives aba and >= gives bab. 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]
SensAI
Beta
Tap the mic to stop voice mode