Introduction
The Longest Palindromic Substring problem is one of the most frequently asked DSA interview questions in string algorithms. It checks your understanding of string traversal, symmetry, and optimization techniques.
In simple words, this problem asks you to find the longest part of a string that reads the same forward and backward.
This article explains the problem in plain language, with clear examples and an optimized solution commonly expected in interviews.
What is a Palindrome?
A palindrome is a word or string that remains the same when reversed.
This means:
The first character matches the last character
The second character matches the second last character
And so on
Examples of Palindromes
"madam"
"level"
"racecar"
"aa"
What is the Longest Palindromic Substring Problem?
You are given a string. Your task is to identify the longest palindrome.
Important points:
The substring must be continuous
There can be more than one palindrome, but you return the longest one
Example
Input: "babad"
Output: "bab"
Explanation
"bab" is a palindrome
"aba" is also a palindrome
Both have the same length, so returning either one is acceptable
Brute Force Approach (Easy but Slow)
In the brute-force approach, we check all possible substrings and verify whether each one is a palindrome.
Problems with Brute Force
Too many substrings
Checking palindrome repeatedly is costly
Time Complexity becomes O(n³)
This approach is not suitable for interviews.
Optimized Approach: Expand Around Center
The most commonly expected solution in interviews is the Expand Around Center approach.
Key Idea
Every palindrome expands from its center
A center can be:
One character (odd-length palindrome)
Two characters (even-length palindrome)
We try to expand around each possible center.
Step-by-Step Explanation
Steps:
Start from each character in the string
Treat it as the center of a palindrome
Expand left and right while characters match
Repeat the process for two-character centers
Track the longest palindrome found
This approach avoids unnecessary checks.
Dry Run Example
String: "babad"
Centers and palindromes:
Center at index 1 → "bab"
Center at index 2 → "aba"
Longest length found = 3
Join the conversation! Your thoughts help the community grow.