Longest Palindromic Substring

Given a string s, return its longest palindromic substring: the longest run of consecutive characters of s that reads the same forwards and backwards.

A single character is always a palindrome, so the answer is never empty. If several different substrings share the maximum length, returning any one of them is accepted.

Example 1

Input: s = "bananas" Output: "anana" Why: "anana" (length 5) reads the same in both directions; nothing longer does.

Example 2

Input: s = "xy" Output: "x" (any valid answer is accepted) Why: "xy" has no palindrome longer than one character, so "x" or "y" are both accepted.

Example 3

Input: s = "indeed" Output: "deed" Why: An even-length palindrome: "deed" is centred between the two e's.

Constraints

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

Pattern Path · Dynamic Programming · problem 151 of 169

Checking every substring is O(n³). Instead of guessing where a palindrome starts and ends, think about where its middle is.
A palindrome mirrors around its centre. From a centre, you can grow outward while the characters on both sides match.
There are 2n − 1 centres: each character (odd lengths) and each gap between neighbours (even lengths). Expand from every one and keep the longest.
Target: O(n²) time, O(1) extra space.

Start simple

Test every substring by comparing it with its reverse: O(n²) substrings × O(n) check = O(n³) time.

The key idea

Every palindrome has a centre, and stripping its two end characters leaves a shorter palindrome around the same centre. So, starting from a centre, you can grow a palindrome one ring at a time: keep extending while s[left] == s[right], and the moment they differ you have found the longest palindrome at that centre. Nothing larger at that centre can exist, because it would contain the mismatched pair.

Centres come in two kinds. An odd-length palindrome like "level" is centred on a character (start with left = right = i); an even-length one like "deed" is centred between two characters (start with left = i, right = i + 1). Trying both kinds at every position covers every palindrome in the string.

Each expansion is at most O(n), and there are about 2n centres, giving O(n²) time with only a few indices of extra memory. That beats the O(n²)-memory DP table that marks is_pal[i][j], and is fast enough for n = 1000. (Manacher’s algorithm reaches O(n) but is rarely expected.)

Complexity

  • Time: O(n²)
  • Space: O(1)

Python

class Solution:
    def longestPalindrome(self, s):
        def expand(left, right):
            # Grow outward while both ends match; return the palindrome's bounds.
            while left >= 0 and right < len(s) and s[left] == s[right]:
                left -= 1
                right += 1
            return left + 1, right   # the last step went one too far on each side

        best_start, best_end = 0, 1
        for i in range(len(s)):
            for start, end in (expand(i, i), expand(i, i + 1)):   # odd and even centres
                if end - start > best_end - best_start:
                    best_start, best_end = start, end
        return s[best_start:best_end]

JavaScript

var longestPalindrome = function(s) {
  // Grow outward while both ends match; return [start, end) of the palindrome.
  const expand = (left, right) => {
    while (left >= 0 && right < s.length && s[left] === s[right]) {
      left--;
      right++;
    }
    return [left + 1, right]; // the last step went one too far on each side
  };

  let bestStart = 0, bestEnd = 1;
  for (let i = 0; i < s.length; i++) {
    for (const [start, end] of [expand(i, i), expand(i, i + 1)]) { // odd and even centres
      if (end - start > bestEnd - bestStart) {
        bestStart = start;
        bestEnd = end;
      }
    }
  }
  return s.slice(bestStart, bestEnd);
};

What the interviewer is checking

The interviewer looks for the shift from enumerating substrings to enumerating centres, and for handling even-length palindromes without a separate special case.

Mistakes to avoid

  • Only expanding around characters and missing even-length palindromes like "deed".
  • Confusing substring (contiguous) with subsequence (can skip characters).
  • Off-by-one when converting the final left/right (one step past the palindrome) back into a slice.

Follow-ups to expect

  • Can you do it in linear time? (Manacher's algorithm.)
  • Count all palindromic substrings instead. (Same expansion, add counts.)
  • Longest palindromic subsequence? (Interval DP over i, j.)

In real software

Palindrome detection around centres is used in DNA analysis, where reverse-complement palindromes mark restriction sites, and in text-processing tools that look for mirrored patterns.

Practice next

Next Post Previous Post
No Comment
Add Comment
comment url