Longest Palindromic Substring

Pattern: Palindromes

medium

Every palindrome has a centre, a character or the gap between two. Grow outwards from each of the 2n - 1 centres while both ends match, and keep the longest.

The problem

Given a string s, return its longest substring that is a palindrome. For example, "babad" gives "bab" ("aba" is just as long), and "cbbd" gives "bb".

The function name longestPalindrome matches LeetCode. Use the link above for the exact statement and limits. LeetCode accepts any longest answer. So that the tests have one answer, this guide returns the leftmost one.

Think first

  • How would you check every substring, and what would that cost?
  • If s[l..r] is a palindrome, what must be true of s[l + 1..r - 1]?
  • Where can a palindrome of even length have its centre?

Hints

    Brute force, and why it fails

    Check every substring by reversing it: O(n³). A DP table of "is s[i..j] a palindrome" is O(n²) time and memory. Expanding around centres is O(n²) time and O(1) memory. Manacher's algorithm (see its lesson) does O(n).

    The key insight

    Palindromes are built from the middle out, so growing from each centre finds every palindrome without rechecking its inside.

    Dry run

    b0l, r
    a1 
    b2 
    a3 
    d4 
    bestb

    s = babad. Try each centre in turn. Centre b at index 0 gives just b.

    Step 1 of 4

    The plan

    bestStart = 0, bestLen = 1
    for i from 0 to n - 1:
        for (l, r) in ((i, i), (i, i + 1)):
            while l >= 0 and r < n and s[l] == s[r]: l = l - 1; r = r + 1
            if r - l - 1 > bestLen: bestLen = r - l - 1; bestStart = l + 1
    return s[bestStart .. bestStart + bestLen - 1]
    

    Complexity

    Time
    O(n²)
    Space
    O(1)

    There are 2n - 1 centres, and each can grow up to n / 2 steps, as in "aaaa…".

    Edge cases

    • One character: itself.
    • No two equal characters, as in "ac": the first character.
    • All equal: the whole string.
    I've built my logic, show the code

    Java

    class Solution {
        public String longestPalindrome(String s) {
            int bestStart = 0, bestLen = 1;
            for (int c = 0; c < s.length(); c++) {
                for (int odd = 0; odd <= 1; odd++) {               // centre on a character, or between two
                    int l = c, r = c + 1 - odd;                    // odd = 1: l = r = c; odd = 0: l = c, r = c + 1
                    while (l >= 0 && r < s.length() && s.charAt(l) == s.charAt(r)) { l--; r++; }
                    int len = r - l - 1;                           // the last window that matched
                    if (len > bestLen) { bestLen = len; bestStart = l + 1; }   // strictly longer keeps the leftmost
                }
            }
            return s.substring(bestStart, bestStart + bestLen);
        }
    }

    C++

    class Solution {
    public:
        string longestPalindrome(string s) {
            int n = static_cast<int>(s.size()), bestStart = 0, bestLen = 1;
            for (int c = 0; c < n; c++) {
                for (int odd = 0; odd <= 1; odd++) {               // centre on a character, or between two
                    int l = c, r = c + 1 - odd;                    // odd = 1: l = r = c; odd = 0: l = c, r = c + 1
                    while (l >= 0 && r < n && s[l] == s[r]) { l--; r++; }
                    int len = r - l - 1;                           // the last window that matched
                    if (len > bestLen) { bestLen = len; bestStart = l + 1; }   // strictly longer keeps the leftmost
                }
            }
            return s.substr(bestStart, bestLen);
        }
    };

    Python

    class Solution:
        def longestPalindrome(self, s: str) -> str:
            best_start, best_len = 0, 1
            for c in range(len(s)):
                for l, r in ((c, c), (c, c + 1)):   # centre on a character, or between two
                    while l >= 0 and r < len(s) and s[l] == s[r]:
                        l -= 1
                        r += 1
                    if r - l - 1 > best_len:        # strictly longer keeps the leftmost
                        best_len, best_start = r - l - 1, l + 1
            return s[best_start:best_start + best_len]

    Common mistakes

    • Skipping gap centres, which misses "bb" in "cbbd".
    • Using s[l .. r] after the loop instead of s[l + 1 .. r - 1].
    • Using ≥ when updating the best, which returns the rightmost tie instead of the leftmost.

    Similar problems