Longest Palindromic Substring

Expand around each center (n odd-center, n-1 even-center); track the longest match.

Medium
Time O(n^2) Space O(1)
LeetCode
4 min read
string expand-around-center dp

Problem#

Return the longest palindromic substring of s.

Examples#

  • "babad""bab" or "aba".
  • "cbbd""bb"; "a""a".

Constraints#

  • 1 <= s.length <= 1000.

Approach#

Expand around 2n - 1 centers (each position and each gap between positions). For each center, walk outward while both sides match; record the longest.

Solution#

Longest Palindromic Substring
class Solution {
public:
string longestPalindrome(string s) {
int n = s.size(), bestStart = 0, bestLen = 1;
auto expand = [&](int l, int r) {
while (l >= 0 && r < n && s[l] == s[r]) { --l; ++r; }
int len = r - l - 1;
if (len > bestLen) { bestLen = len; bestStart = l + 1; }
};
for (int i = 0; i < n; ++i) {
expand(i, i);
expand(i, i + 1);
}
return s.substr(bestStart, bestLen);
}
};

Editorial#

Expanding around centers covers both odd and even palindromes uniformly. Manacher’s algorithm achieves O(n) but is rarely needed inside the n <= 1000 constraint; the simple expansion is O(n^2) and one-pass clear.

Complexity#

  • Time: O(n^2).
  • Space: O(1).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.