Skip to main content
52

Longest Palindromic Substring

Mediumdynamic programmingstrings

Your code isn't saved yet: refreshing or leaving the page resets it. Saved progress comes with user accounts.

This problem uses:1-D Dynamic ProgrammingRead the beginner guide

Given a string s, return its longest palindromic substring.

Understand the problem

  • A palindrome reads the same forwards and backwards: "bab", "abba", "x".
  • A substring is a contiguous run of characters: in "cbabd", "bab" is a substring, but "cbd" isn't (it skips letters).
  • You want the longest substring that is a palindrome. The tests guarantee there's only one longest.
  • Any single character is a palindrome, so the answer always has at least length 1.

Example 1

text
Input:  s = "cbabd"
Output: "bab"

Example 2

text
Input:  s = "cbbd"
Output: "bb"

Palindromes can have even length too: "bb" reads the same both ways.

Example 3

text
Input:  s = "a"
Output: "a"

Constraints

  • 1 <= s.length <= 1000
  • s contains English letters and digits.

Hints

Stuck? Open one hint at a time. Each one gives away a little more than the last.

    The idea in one sentence

    Every palindrome is mirrored around its center, so try every possible center and grow outward while the characters on both sides match, keeping the longest one found.

    The naive approach (and why it's slow)

    Check every substring: there are about n²/2 of them, and checking each one takes up to n comparisons. That's O(n³): about 170 million steps for n = 1000.

    The key insight: expand around the center

    A palindrome is symmetric around its center. That means you can build it from the middle out:

    • Start at a center.
    • If the characters just to the left and just to the right match, the palindrome grows by one on each side.
    • Keep going until they don't match (or you hit the edge of the string).

    There are two kinds of center:

    KindExampleCenter
    one character (odd length)"aba"the b
    a gap (even length)"abba"between the two bs

    For a string of length n, there are n character centers and n - 1 gaps: 2n - 1 centers in total. Expand from each and keep the longest.

    The code's trick for both kinds at once: loop center from 0 to 2n - 2. Start with left = floor(center / 2) and right = left + (center % 2). For an even center, left === right (a character); for an odd one, right = left + 1 (a gap).

    Step by step

    s = "cbabd" (indexes 0 to 4). Only the centers that find something longer than 1 are interesting:

    CenterExpansionsPalindrome found
    c (index 0)edge reached"c" (1)
    gap between c and bc ≠ b, stop immediately(none)
    b (index 1)c ≠ a, stop"b" (1)
    a (index 2)b = b ✓, then c ≠ d, stop"bab" (3)
    b (index 3)a ≠ d, stop"b" (1)
    other gaps, dnothing longer

    Longest: "bab".

    The code

    The reference solution is below, with comments on every important line.

    How fast is it?

    • Time: O(n²). 2n - 1 centers, and each can expand up to n/2 times. In practice most expansions stop almost immediately.
    • Memory: O(1). Just a few indexes.

    Common mistakes

    • Forgetting even-length palindromes. Only expanding around characters misses "bb" in "cbbd".
    • Off-by-one when computing the result. When the loop stops, left and right are one step past the palindrome. It starts at left + 1 and has length right - left - 1.

    Going deeper

    • The DP view: s[i..j] is a palindrome when s[i] === s[j] and s[i+1..j-1] is a palindrome. A table of n × n booleans filled from short substrings to long ones also solves this in O(n²), but uses O(n²) memory. Expanding around centers applies the same rule, from the inside out, without the table.
    • Manacher's algorithm solves it in O(n), but it's rarely expected in interviews.
    • Palindromic Substrings uses the exact same expansion, but counts palindromes instead of keeping the longest.

    Reference solution

    js
    /**
     * @param {string} s
     * @return {string}
     */
    export default function longestPalindrome(s) {
      let start = 0 // where the longest palindrome so far begins
      let length = 0 // and how long it is
      // 2n - 1 centers: even values are a character (odd-length palindromes),
      // odd values are the gap between two characters (even-length palindromes).
      for (let center = 0; center < 2 * s.length - 1; center++) {
        let left = Math.floor(center / 2)
        let right = left + (center % 2)
        // Grow outward while both sides match.
        while (left >= 0 && right < s.length && s[left] === s[right]) {
          left--
          right++
        }
        // left and right stopped one step PAST the palindrome, so it's s[left + 1 .. right - 1].
        if (right - left - 1 > length) {
          start = left + 1
          length = right - left - 1
        }
      }
      return s.slice(start, start + length)
    }
    ts
    export default function longestPalindrome(s: string): string {
      let start = 0 // where the longest palindrome so far begins
      let length = 0 // and how long it is
      // 2n - 1 centers: even values are a character (odd-length palindromes),
      // odd values are the gap between two characters (even-length palindromes).
      for (let center = 0; center < 2 * s.length - 1; center++) {
        let left = Math.floor(center / 2)
        let right = left + (center % 2)
        // Grow outward while both sides match.
        while (left >= 0 && right < s.length && s[left] === s[right]) {
          left--
          right++
        }
        // left and right stopped one step PAST the palindrome, so it's s[left + 1 .. right - 1].
        if (right - left - 1 > length) {
          start = left + 1
          length = right - left - 1
        }
      }
      return s.slice(start, start + length)
    }
    python
    def longest_palindrome(s: str) -> str:
        start, length = 0, 0  # where the longest palindrome so far begins, and its length
        # 2n - 1 centers: even values are a character (odd-length palindromes),
        # odd values are the gap between two characters (even-length palindromes).
        for center in range(2 * len(s) - 1):
            left = center // 2
            right = left + center % 2
            # Grow outward while both sides match.
            while left >= 0 and right < len(s) and s[left] == s[right]:
                left -= 1
                right += 1
            # left and right stopped one step PAST the palindrome, so it's s[left + 1 : right].
            if right - left - 1 > length:
                start, length = left + 1, right - left - 1
        return s[start : start + length]