AlgoInsight

DSA problem

Longest Palindromic Substring

MediumTwo PointersPattern: Two Pointerstop600AmazonMicrosoftAppleGoogleBloomberg

Given a string s, return the longest palindromic substring in s. If there are multiple such substrings of equal maximum length, you may return any one.

A palindrome reads the same forward and backward. A substring is a contiguous slice — unlike a subsequence, you cannot skip characters in the middle.

The brute force checks each of O(n^2) substrings for palindromicity in O(n), costing O(n^3). The standard O(n^2) approaches mirror the techniques for counting palindromic substrings:

Expand Around Center. Every palindrome has a center, so iterate over the 2n - 1 possible centers (each character for odd length, each adjacent pair for even length) and expand outward while characters match. Track the best length and starting index seen so far. This solves the problem in O(n^2) time and O(1) extra space — the recommended production-grade solution.

2D DP. Define dp[i][j] as a boolean for "s[i..j] is a palindrome", filled by increasing length. The DP is conceptually clean but uses O(n^2) space.

Manacher's algorithm achieves O(n) but is rarely required at the typical constraint range of n <= 1000.

Examples

Example 1
Input: s = "babad"
Output: "bab"
Explanation: "bab" is a valid longest palindromic substring of length 3. "aba" is also a correct answer with the same length.
Example 2
Input: s = "cbbd"
Output: "bb"
Explanation: The longest palindromic substring is "bb" with length 2; no longer palindrome exists.
Example 3
Input: s = "a"
Output: "a"
Explanation: A single character is trivially the longest palindromic substring of itself.

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

stringdynamic-programmingpalindrometwo-pointers

Browse all DSA problems