Longest Palindromic Substring
Solve it by expanding around each center in O(n²) time and O(1) space, then with a dynamic programming table.
Given a string, find the longest part of it that reads the same forwards and backwards. It is one of the most common string questions in coding interviews, and it is a good one to learn properly because it teaches two ideas you will reuse everywhere: growing an answer outward from a center, and building a table of smaller answers.
This tutorial solves it three ways in JavaScript. A brute-force version first, so the problem is concrete. Then expand around the center, which is the answer most interviewers expect. Then dynamic programming, which is slower here but teaches a pattern you will need for harder problems.
The problem
Given a string s, return the longest substring of s that is a palindrome.
"babad"returns"bab"."aba"is also correct, since both have length 3."cbbd"returns"bb"."a"returns"a". A single character is always a palindrome.
Two words matter here:
- Palindrome: a sequence that reads the same in both directions, like
"racecar"or"abba". - Substring: a run of characters that are next to each other in the original string. In
"babad","bab"is a substring."bbd"is not, because those letters are not adjacent.
The usual constraint is a length of up to 1,000 characters. That number is a hint: it tells you an O(n²) solution is fine and an O(n³) one is not.
Brute force: check every substring
The direct approach is to try every start and end position, check whether that substring is a palindrome, and keep the longest one.
function isPalindrome(s, left, right) {
while (left < right) {
if (s[left] !== s[right]) return false;
left++;
right--;
}
return true;
}
function longestPalindromeBruteForce(s) {
let best = "";
for (let i = 0; i < s.length; i++) {
for (let j = i; j < s.length; j++) {
if (j - i + 1 > best.length && isPalindrome(s, i, j)) {
best = s.slice(i, j + 1);
}
}
}
return best;
}
It is correct, and it is slow. There are about n²/2 substrings, and checking each one can take up to n steps, so the total is O(n³) time. For a 1,000-character string that is in the hundreds of millions of character comparisons.
The waste is easy to see. To check "racecar", the loop compares r with r, then a with a, and so on. Later it checks "aceca", which is the same middle part, from scratch. The work for the inside of a palindrome gets repeated for every longer string that contains it. Both better solutions remove that repetition, in different ways.
Approach 1: expand around the center
Look at a palindrome from the middle instead of from the ends. "racecar" has e in the center, a matching c on each side, then a matching a on each side, then a matching r. Every palindrome is a center with matching characters added symmetrically around it.
So instead of checking substrings, pick each possible center and grow outward while the two sides match. The point where they stop matching is the edge of the longest palindrome at that center.
There is one detail: palindromes come in two shapes.
- Odd length, like
"aba": the center is one character. - Even length, like
"abba": the center is the gap between two characters.
A string of length n has n single-character centers and n - 1 gaps, so about 2n centers in total. Expanding from each one handles both shapes.
function longestPalindrome(s) {
if (s.length < 2) return s;
let start = 0;
let maxLength = 1;
function expand(left, right) {
// Grow outward while both sides are in range and match.
while (left >= 0 && right < s.length && s[left] === s[right]) {
left--;
right++;
}
// The loop stopped one step too far on each side.
const length = right - left - 1;
if (length > maxLength) {
maxLength = length;
start = left + 1;
}
}
for (let center = 0; center < s.length; center++) {
expand(center, center); // odd length, e.g. "aba"
expand(center, center + 1); // even length, e.g. "abba"
}
return s.slice(start, start + maxLength);
}
The line most people get wrong is const length = right - left - 1. When the loop ends, left and right have each moved one position past the palindrome, because that is the step where the comparison failed or the index ran off the string. The palindrome itself runs from left + 1 to right - 1, and its length is (right - 1) - (left + 1) + 1, which simplifies to right - left - 1.
Tracing it on "babad"
| Center | Expansion | Palindrome found |
|---|---|---|
index 0, b | stops at once, the left side is out of range | "b" |
index 1, a | b matches b, then the left side runs out | "bab", length 3 |
index 2, b | a matches a, then b and d differ | "aba", length 3, not longer |
| gaps between letters | no two neighbours match | nothing |
The answer is "bab". The function keeps the first palindrome of the maximum length it finds, which is why it returns "bab" and not "aba".
Cost
There are about 2n centers, and an expansion can take up to n steps, so the worst case is O(n²) time. It only stores two numbers, so the extra space is O(1). In practice it is faster than the worst case suggests, because most expansions stop after one or two comparisons.
Approach 2: dynamic programming
The second way to remove the repeated work is to record answers as you go. This uses a rule that comes straight from the definition:
A substring is a palindrome if its first and last characters match and the part between them is also a palindrome.
"racecar" is a palindrome because r equals r and "aceca" is a palindrome. That means the answer for a long substring depends only on the answer for a shorter one. Store the short answers in a table, and every long answer becomes a single lookup.
Let dp[i][j] be true when the substring from index i to index j is a palindrome. The rule becomes:
dp[i][j] = (s[i] === s[j]) && dp[i + 1][j - 1]
The rule needs a starting point, because dp[i + 1][j - 1] has to exist before dp[i][j] can use it. Two base cases cover the shortest substrings:
- Length 1: every single character is a palindrome, so
dp[i][i] = true. - Length 2: two characters form a palindrome only if they are equal.
Then fill the table by substring length, from 3 up to n. That order guarantees the inner substring, which is two characters shorter, is always already filled in.
function longestPalindromeDP(s) {
const n = s.length;
if (n < 2) return s;
const dp = Array.from({ length: n }, () => new Array(n).fill(false));
let start = 0;
let maxLength = 1;
// Length 1: every character is a palindrome.
for (let i = 0; i < n; i++) dp[i][i] = true;
// Length 2: a palindrome only if both characters match.
for (let i = 0; i < n - 1; i++) {
if (s[i] === s[i + 1]) {
dp[i][i + 1] = true;
if (maxLength < 2) {
start = i;
maxLength = 2;
}
}
}
// Length 3 and up: the ends match and the inside is a palindrome.
for (let length = 3; length <= n; length++) {
for (let i = 0; i + length - 1 < n; i++) {
const j = i + length - 1;
if (s[i] === s[j] && dp[i + 1][j - 1]) {
dp[i][j] = true;
if (length > maxLength) {
start = i;
maxLength = length;
}
}
}
}
return s.slice(start, start + maxLength);
}
A common mistake is to fill the table row by row, with i from 0 to n - 1 in the outer loop. Then dp[i][j] asks for dp[i + 1][j - 1] from a row that has not been filled yet, and the answers come out wrong. Looping by length, or looping i from the end of the string backwards, avoids that.
Cost
The table has n² cells and each takes constant time to fill, so this is O(n²) time and O(n²) space. For n = 1,000 that is a million booleans.
Which one to use
| Approach | Time | Extra space | When it fits |
|---|---|---|---|
| Brute force | O(n³) | O(1) | Only to explain the problem |
| Expand around the center | O(n²) | O(1) | The default answer, in interviews and in code |
| Dynamic programming | O(n²) | O(n²) | When you need palindrome answers for many substrings, not just the longest |
Expand around the center wins on this problem. It has the same time bound as the table, uses no extra memory, and is shorter to write correctly. In one test run on a 2,000-character string, it took about 3.5 ms and the DP version about 25 ms, mostly because building and walking the table costs memory traffic.
The DP version is still worth knowing. The same table answers "is s[i..j] a palindrome?" for every i and j, and that is exactly what related problems need. Palindrome Partitioning and Count Palindromic Substrings both build on it.
There is also an O(n) solution, Manacher's algorithm, which reuses information from palindromes it has already found so it never expands the same characters twice. It is rarely expected in interviews and is easy to get wrong. If you can explain expand around the center clearly and mention that a linear-time algorithm exists, you have covered what most interviewers are looking for.
The same idea, a different question: counting palindromes
A close relative of this problem asks how many palindromic substrings a string has, rather than which one is longest. "abc" has 3, one per letter. "aaa" has 6: three single letters, two "aa", and one "aaa".
Expand around the center answers it with a one-line change. Every time an expansion takes a successful step, it has found one more palindrome, so count the steps instead of tracking the longest result.
function countPalindromicSubstrings(s) {
let count = 0;
function expand(left, right) {
while (left >= 0 && right < s.length && s[left] === s[right]) {
count++; // every successful step is one more palindrome
left--;
right++;
}
}
for (let center = 0; center < s.length; center++) {
expand(center, center);
expand(center, center + 1);
}
return count;
}
This is why the center idea is worth learning as a pattern and not as a single answer. The loop that finds the longest palindrome also counts them, and with small changes it can list them or find the longest one that starts at a given index. When a new palindrome problem appears, the first question to ask is whether growing outward from every center gives you the information you need.
How to present it in an interview
The code is short, so most of the marks come from how you get there. A clear order that works well:
- Restate the problem with an example. Say that
"babad"has two valid answers, which shows you have thought about ties. - Name the brute force and its cost. Every substring, checked end to end, is O(n³). You do not need to write it, only to show you know why it is too slow.
- Point out the repeated work. Checking
"racecar"and then"aceca"repeats the same comparisons. That observation is what leads to both faster solutions. - Propose expand around the center. Explain the two kinds of center before you write any code, because forgetting the even case is the most common bug.
- State the complexity and test the edges. O(n²) time and O(1) space. Then walk through
"cbbd"and"a"out loud.
If there is time left, mention that the DP table gives the same time bound with more memory, and that Manacher's algorithm brings it down to O(n). Saying that you would choose the simpler solution for real code, because it is easier to get right, is a good engineering answer, not a weak one.
Test your solution
These cases cover the edges that usually break an implementation:
const cases = [
["babad", ["bab", "aba"]], // two valid answers of the same length
["cbbd", ["bb"]], // even-length palindrome
["a", ["a"]], // single character
["ac", ["a", "c"]], // no palindrome longer than 1
["racecar", ["racecar"]], // the whole string
["aaaa", ["aaaa"]], // repeated characters, even length
];
for (const [input, accepted] of cases) {
const result = longestPalindrome(input);
console.log(accepted.includes(result) ? "pass" : "FAIL", input, "->", result);
}
If "cbbd" fails, the even-length center is missing. If "aaaa" returns "aaa", the length calculation after the expansion is off by one.
What to take away
- Every palindrome grows outward from a center, and there are about 2n centers: n characters and n - 1 gaps.
- Check both shapes. Odd palindromes have a character in the middle, even ones have a gap.
- Expand around the center is O(n²) time and O(1) space, and it is the answer to give first.
- The DP rule is that a substring is a palindrome when its ends match and its inside is a palindrome. Fill the table by length so the inside is always ready.
- Know that Manacher's algorithm exists and runs in O(n), even if you never write it.