Longest Palindromic Substring (LeetCode 5): Solution and Explanation

Medium
String
Dynamic Programming

Given a string, return the longest contiguous piece of it that reads the same forward and backward. If several substrings tie for the longest length, any one of them is acceptable.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

Intuition

The brute force checks every substring: there are about n² / 2 of them, and verifying each is a palindrome takes O(n), so the total is O(n³). That is too slow for strings of length 1,000 and also repeats a lot of work, since checking 'abcba' re-checks 'bcb' inside it.

The key observation is that every palindrome is symmetric around its center. If you fix the center and grow outward one character on each side, you are extending a palindrome only as long as the next pair of characters matches, and the moment they differ, no wider substring around that center can be a palindrome either. So instead of enumerating substrings, enumerate centers and expand.

There are two kinds of centers. An odd-length palindrome like 'aba' is centered on a single character, and an even-length one like 'abba' is centered between two characters. That gives 2n - 1 possible centers, and you expand from each. Each expansion is at most O(n), so the whole algorithm is O(n²) with no extra memory beyond a start index and a length.

Approach: Expand around center

  1. If the string has fewer than two characters, return it as is.
  2. Track the best palindrome with start = 0 and max_len = 1.
  3. Define expand(left, right) that loops while both indices are in bounds and s[left] == s[right].
  4. Inside the loop, if the current window right - left + 1 is longer than max_len, record start = left and the new length, then move left down and right up.
  5. For every index i, call expand(i, i) for odd lengths and expand(i, i + 1) for even lengths.
  6. Return the slice s[start:start + max_len].

Step-by-step example

s = "babad"
  1. At i = 0, the odd expansion only covers 'b', which does not beat length 1, and the even expansion fails because 'b' and 'a' differ.
  2. At i = 1, the odd expansion first covers 'a', then compares s[0] = 'b' with s[2] = 'b'. They match, so 'bab' of length 3 is recorded with start = 0. The next step would go out of bounds.
  3. At i = 2, the odd expansion grows to 'aba', which also has length 3 but is not longer, so the best stays 'bab'. Comparing s[0] = 'b' with s[4] = 'd' stops it.
  4. The remaining centers, including all the even ones, fail on their first or second comparison, so the function returns 'bab'.

Code: Python, Java, C++

1class Solution:
2    def longestPalindrome(self, s: str) -> str:
3        if len(s) < 2:
4            return s
5
6        start, max_len = 0, 1
7
8        def expand(left, right):
9            nonlocal start, max_len
10            while left >= 0 and right < len(s) and s[left] == s[right]:
11                if right - left + 1 > max_len:
12                    start = left
13                    max_len = right - left + 1
14                left -= 1
15                right += 1
16
17        for i in range(len(s)):
18            expand(i, i)      # Odd length
19            expand(i, i + 1)  # Even length
20
21        return s[start:start + max_len]

Time and space complexity

Time

O(n²)

There are 2n - 1 centers, and each expansion can take up to O(n) steps when the string is something like all the same letter. Most real strings stop expanding much sooner.

Space

O(1)

Only a few integer variables are kept. The answer is extracted with a single slice at the end.

Other approaches

Dynamic programming table (time O(n²), space O(n²))

Let dp[i][j] be true when s[i:j+1] is a palindrome, which holds when the end characters match and dp[i+1][j-1] is true. Fill it by increasing length. It runs in the same O(n²) time but needs an n by n table.

Manacher's algorithm (time O(n), space O(n))

Insert separators so every palindrome has odd length, then reuse mirror information from the rightmost known palindrome to skip redundant expansions. It achieves linear time but is rarely expected in interviews because it is easy to get subtly wrong.

Common mistakes

  • Expanding only around single characters. Without the expand(i, i + 1) call, even-length answers such as 'bb' in 'cbbd' are missed.
  • Recording the window after the loop exits. At that point left and right have already moved past the palindrome, so you must record inside the loop or adjust by one on each side.
  • Building substrings inside the loop. Slicing on every step adds an O(n) cost per expansion; tracking only start and max_len avoids that.
  • Confusing this with the longest palindromic subsequence. Substrings must be contiguous, so the subsequence DP gives the wrong answer here.

Frequently asked questions

What is the fastest way to find the longest palindromic substring?

Manacher's algorithm runs in O(n) time. In practice, expanding around centers in O(n²) is the expected interview answer because it is short, uses O(1) space and is fast enough for strings of a few thousand characters.

Why are there 2n - 1 centers?

Each of the n characters can be the middle of an odd-length palindrome, and each of the n - 1 gaps between neighbors can be the middle of an even-length one. Together that makes 2n - 1.

Is expand around center better than dynamic programming?

Both are O(n²) time, but expanding uses O(1) space instead of an n by n table and tends to run faster because it stops early. The DP version is useful when you also need to answer many palindrome queries about the same string.

What is the difference between palindromic substring and subsequence?

A substring is a contiguous block of characters, while a subsequence may skip characters. The longest palindromic subsequence of 'babad' has length 3 as well, but in general it can be much longer than the longest palindromic substring.