Skip to main content

Longest Palindromic Substring - Solution & Explanation

MediumTwo PointersStringDynamic Programming20 min readAsked at: Amazon, Microsoft, Apple +79
Practice this problem

Problem Statement

Given a string s, return the longest palindromic substring in s.

 

Example 1:

Input: s = "babad"
Output: "bab"
Explanation: "aba" is also a valid answer.

Example 2:

Input: s = "cbbd"
Output: "bb"

 

Constraints:

  • 1 <= s.length <= 1000
  • s consist of only digits and English letters.

Approach Overview

Problem Overview: Given a string s, return the longest substring that reads the same forward and backward. The substring must be contiguous, so you cannot rearrange characters or skip indices.

This problem sits at the intersection of string manipulation and palindrome detection. The challenge is checking all possible centers efficiently without recomputing the same substrings repeatedly.

Approach 1: Expand Around Center (Time: O(n2), Space: O(1))

A palindrome mirrors around its center. Every palindrome can have either one center (odd length like aba) or two centers (even length like abba). Iterate through the string and treat each index as a potential center. Expand outward using two pointers while the characters match.

For each index i, run two expansions: one with (i, i) for odd-length palindromes and another with (i, i+1) for even-length palindromes. Track the longest substring found during these expansions. Each expansion moves the two pointers outward until the characters differ or boundaries are reached.

This approach avoids storing intermediate states and checks only meaningful palindrome candidates. In the worst case (e.g., aaaaa) each expansion scans many characters, leading to O(n2) time, but the constant factors are small and memory usage stays O(1).

Approach 2: Dynamic Programming (Time: O(n2), Space: O(n2))

The dynamic programming approach builds a table dp[i][j] indicating whether substring s[i..j] is a palindrome. Single characters are palindromes, and pairs of equal characters form length-2 palindromes. For longer substrings, a substring is a palindrome if s[i] == s[j] and dp[i+1][j-1] is true.

Fill the DP table by increasing substring length. Each time a palindrome is confirmed, update the longest substring indices. This method ensures every substring is evaluated exactly once.

The main advantage is clarity: the palindrome property is expressed directly through subproblems. The downside is memory usage, since the DP table requires O(n2) space. For long strings this becomes expensive compared to the center-expansion approach.

Recommended for interviews: Expand Around Center is the solution most interviewers expect. It demonstrates understanding of palindrome symmetry and avoids unnecessary memory. Dynamic Programming shows strong problem decomposition but is rarely preferred due to its O(n2) space cost. Mentioning Manacher’s algorithm (O(n) time) can earn bonus points, though implementing it correctly during interviews is uncommon.

Approach 1: Expand Around Center

This approach is based on the observation that a palindrome mirrors around its center. Therefore, if we choose a center, we can expand outward to check for the longest possible palindrome. We can have centers between each two characters as well as on each character to cater for even and odd length palindromes.

The solution iterates over each character, considering it as a possible center of a palindrome. It tries to expand around it for both odd and even lengths. We maintain the longest found palindrome's start and end indices, which are used to construct the result substring in the end.

Code

C

C++

Java

Python

C#

JavaScript

Complexity

Time Complexity: O(n^2) because we potentially expand around n centers.

Space Complexity: O(1), aside from the space required for the output string.

Try this approach in the editor →

Approach 2: Dynamic Programming

In this approach, a 2D DP table is constructed where dp[i][j] is true if the string s[i...j] is a palindrome. Each entry is dependent on smaller substring checks. This method leverages overlapping subproblems.

We make use of a DP table that captures the palindrome status for each (i,j) substring. The status gets updated from prior adjacent matches. Substring boundaries clarify palindromes, storing the starting position and length of the longest identified palindrome.

Code

C

C++

Java

Python

C#

JavaScript

Go

TypeScript

Rust

Nim

Complexity

Time Complexity: O(n^2) due to the complete 2D table scan.
Space Complexity: O(n^2) as the DP table fully holds substring truths.

Try this approach in the editor →

Approach 3: Enumerate Palindrome Midpoint

We can enumerate the midpoint of the palindrome, spread to both sides, and find the longest palindrome.

The time complexity is O(n^2), and the space complexity is O(1). Here, n is the length of the string s.

Code

Python

Java

C++

Go

Rust

C#

PHP

Try this approach in the editor →

Complexity Comparison

ApproachComplexity
Expand Around Center

Time Complexity: O(n^2) because we potentially expand around n centers.

Space Complexity: O(1), aside from the space required for the output string.

Dynamic Programming

Time Complexity: O(n^2) due to the complete 2D table scan.
Space Complexity: O(n^2) as the DP table fully holds substring truths.

Enumerate Palindrome Midpoint

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Expand Around CenterO(n^2)O(1)Best general solution. Minimal memory and easy to implement in interviews.
Dynamic ProgrammingO(n^2)O(n^2)Useful when learning DP patterns or when substring states must be reused.
Manacher's AlgorithmO(n)O(n)Optimal theoretical solution. Rarely required in interviews due to implementation complexity.

Video Solution

Longest Palindromic Substring - Python - Leetcode 5NeetCode809,465 views views

Watch 9 more video solutions →

Frequently Asked Questions

Is Longest Palindromic Substring easy or hard?
Longest Palindromic Substring is classified as a Medium problem. The brute force idea is simple, but recognizing the center-expansion insight or building a correct DP table requires stronger string and algorithmic reasoning.
How to solve Longest Palindromic Substring in O(n)?
Manacher’s algorithm solves the problem in linear time by transforming the string and reusing previously computed palindrome radii. It avoids redundant comparisons by leveraging symmetry around known centers. The algorithm runs in O(n) time and O(n) space but is more complex than typical interview solutions.
Longest Palindromic Substring Python or Java solution?
Python and Java implementations usually follow the Expand Around Center technique. For each index, the algorithm expands outward for both odd and even centers and tracks the longest valid substring. This implementation runs in O(n^2) time with constant extra space.
What is the best approach for Longest Palindromic Substring?
Expand Around Center is the most practical approach. It checks palindromes by expanding two pointers outward from every possible center in the string. The algorithm runs in O(n^2) time and O(1) space while remaining simple enough to implement quickly during interviews.
Is Longest Palindromic Substring asked at Google/Amazon/Meta?
Longest Palindromic Substring frequently appears in technical interviews at large tech companies including Google, Amazon, Meta, and Microsoft. Interviewers typically expect the Expand Around Center solution and may discuss the tradeoffs between it and Dynamic Programming.
What data structure is used in Longest Palindromic Substring?
The problem mainly uses string traversal with two-pointer expansion. In the Dynamic Programming approach, a 2D boolean table stores whether substring s[i..j] is a palindrome. No advanced data structures are required for the optimal interview solution.
What is the time complexity of Longest Palindromic Substring?
Most standard solutions run in O(n^2) time. Expand Around Center checks up to 2n centers and expands outward, while Dynamic Programming evaluates every substring once. The optimal theoretical solution, Manacher’s algorithm, achieves O(n) time.

Ready to solve this problem?

Practice Longest Palindromic Substring with our built-in code editor and test cases.

Practice on FleetCode