Longest Palindromic Substring

MediumString DP · Expand Around Centre🧩 String DPLeetCode #5 ↗Updated

Problem

Given a string s, return its longest contiguous piece that reads the same forwards and backwards. If several pieces tie for the maximum length, any one of them is accepted.
Inputs = "babad"Output"bab" ("aba" is also fine)
Inputs = "cbbd"Output"bb"
Inputs = "x"Output"x"

1 ≤ s.length ≤ 1000  ·  s holds only digits and English letters

Try it yourself

Java
class Solution {
    public String longestPalindrome(String s) {
        
    }
}
Your code is saved in this browser.Submit on LeetCode ↗
Key insight
Every palindrome is a mirror around a centre — a single char (odd length) or a gap between two chars (even length). There are only 2n-1 centres, and growing outwards from each one finds every palindrome without any table.
PatternString DP

Instinct Two strings compared char by char (match, edit, interleave) means dp[i][j] over prefixes; one string's palindromes or splits means dp[l][r] or dp[i].

Memory hack Match? Go diagonal. Mismatch? Ask the neighbours. Up drops a char from s, left drops one from t, diagonal uses both.

Open the String DP guide →

Approaches

Brute ForceCheck Every Substring, Longest First

Time O(n3)Space O(1)

Try window lengths from n down to 1 and, for each start, test the window with two pointers. The first palindrome found is guaranteed to be a longest one.

Java
public String longestPalindrome(String s) {
    int n = s.length();
    for (int len = n; len >= 1; len--) {
        for (int i = 0; i + len <= n; i++) {
            if (isPalindrome(s, i, i + len - 1)) return s.substring(i, i + len);
        }
    }
    return "";
}

private boolean isPalindrome(String s, int l, int r) {
    while (l < r) {
        if (s.charAt(l++) != s.charAt(r--)) return false;
    }
    return true;
}

Obviously correct, but the inner palindrome check makes it cubic.

At a glance

LevelApproachTimeSpace
Brute ForceCheck Every Substring, Longest FirstO(n3)O(1)
Better2-D Palindrome TableO(n2)O(n2)
OptimalExpand Around Every CentreO(n2)O(1)
Common pitfalls
  • Forgetting even-length centres — misses answers like "bb".
  • Wrong start index from a centre: use c - (len-1)/2, which works for odd and even.
  • Confusing substring with subsequence — that is a different (LPS 516) problem.
Interview tips
  • Clarify that any one of several tied answers is acceptable.
  • Explain why there are 2n-1 centres, then code the shared expand helper.
  • Note the table's O(n2) memory as the reason to prefer centre expansion.
Pattern
Expand around centre → any question about contiguous palindromes inside one string.
My notes saved in this browser