QuestionsDSA

Longest Palindromic Substring

Expand around centerMediumDSA

Return the longest contiguous substring of s that is a palindrome. e.g. 'babad' → 'bab' (or 'aba'), 'cbbd' → 'bb'.

What it tests

The expand-around-center technique, and remembering there are 2n-1 centers because palindromes can be odd- or even-length.

Approach & answer

A palindrome is symmetric about a center, so instead of checking all O(n^2) substrings for the palindrome property (another O(n) each), fix the center and expand outward while the two sides match. There are 2n-1 centers: n single characters (odd-length palindromes) and n-1 gaps between adjacent characters (even-length). For each center grow left/right pointers while in-bounds and equal, tracking the longest span seen. That is O(n^2) time and O(1) space, and it is the expected interview answer; the O(n) Manacher's algorithm exists but is rarely required. Recognition signal: 'longest/all palindromic substrings' → expand around each of the 2n-1 centers (the same engine COUNTS palindromic substrings by summing every successful expansion). A dp[i][j] = 'is s[i..j] a palindrome' table also works but costs O(n^2) space.

Use this technique when

Finding or counting palindromic substrings → expand around all 2n-1 centers, handling odd and even lengths, tracking the best span.

Complexity

Time O(n²) · Space O(1)

References

js