Longest Palindromic Substring (LeetCode 5): Solution and Explanation
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.
Watch it run step by step
Try your own input and write the code →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
- If the string has fewer than two characters, return it as is.
- Track the best palindrome with
start = 0andmax_len = 1. - Define
expand(left, right)that loops while both indices are in bounds ands[left] == s[right]. - Inside the loop, if the current window
right - left + 1is longer thanmax_len, recordstart = leftand the new length, then moveleftdown andrightup. - For every index
i, callexpand(i, i)for odd lengths andexpand(i, i + 1)for even lengths. - Return the slice
s[start:start + max_len].
Step-by-step example
s = "babad"
- 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.
- 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. - 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.
- 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]1class Solution {
2 private int start = 0, maxLen = 1;
3
4 public String longestPalindrome(String s) {
5 if (s.length() < 2) return s;
6
7 for (int i = 0; i < s.length(); i++) {
8 expand(s, i, i);
9 expand(s, i, i + 1);
10 }
11
12 return s.substring(start, start + maxLen);
13 }
14
15 private void expand(String s, int left, int right) {
16 while (left >= 0 && right < s.length() && s.charAt(left) == s.charAt(right)) {
17 if (right - left + 1 > maxLen) {
18 start = left;
19 maxLen = right - left + 1;
20 }
21 left--;
22 right++;
23 }
24 }
25}1class Solution {
2public:
3 string longestPalindrome(string s) {
4 if (s.length() < 2) return s;
5
6 int start = 0, maxLen = 1;
7
8 auto expand = [&](int left, int right) {
9 while (left >= 0 && right < s.length() && s[left] == s[right]) {
10 if (right - left + 1 > maxLen) {
11 start = left;
12 maxLen = right - left + 1;
13 }
14 left--;
15 right++;
16 }
17 };
18
19 for (int i = 0; i < s.length(); i++) {
20 expand(i, i);
21 expand(i, i + 1);
22 }
23
24 return s.substr(start, maxLen);
25 }
26};Time and space complexity
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.
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
leftandrighthave 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
startandmax_lenavoids 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.