Longest palindromic Subsequence
return longest palindrome
Longest Palindromic Substring
Problem
You are given a string s. Return the longest palindromic substring in s.
A palindrome reads the same from left to right and from right to left. A substring is a block of characters that sit next to each other.
Examples
Example 1
Input: s = "babad"
Output: "bab"
"aba"is also a valid answer.
Example 2
Input: s = "cbbd"
Output: "bb"
Constraints
1 <= s.length <= 1000shas only digits and English letters.
Main Idea
Every palindrome has a center. If we start from the center and move outward, we can check how big the palindrome is.
- Move one step left and one step right.
- If both characters are equal, the palindrome grows.
- If they are different, or we reach the edge, we stop.
There are two kinds of centers:
- Odd length: The center is one character, like
"aba". We start withl = iandr = i. - Even length: The center is between two characters, like
"abba". We start withl = iandr = i + 1.
For a string of length n, there are 2n - 1 centers. We try all of them and keep the longest result.
Brute Force (For Comparison)
We check every substring and test if it is a palindrome.
- There are about
n²substrings, and each check takes up toO(n). - Time Complexity:
O(n³) - Space Complexity:
O(1)
This is slow, even for n = 1000.
Solution: Expand Around Center
var longestPalindrome = function (s) {
let start = 0;
let end = 0;
// grow from the center and return the final palindrome range
function expand(l, r) {
while (l >= 0 && r < s.length && s[l] === s[r]) {
l--;
r++;
}
// l and r are one step too far, so fix them
return [l + 1, r - 1];
}
for (let i = 0; i < s.length; i++) {
// odd length: center is one character
let [l1, r1] = expand(i, i);
// even length: center is between two characters
let [l2, r2] = expand(i, i + 1);
if (r1 - l1 > end - start) {
start = l1;
end = r1;
}
if (r2 - l2 > end - start) {
start = l2;
end = r2;
}
}
return s.slice(start, end + 1);
};
How the Code Works
Step 1: Keep the best range
startandendhold the range of the longest palindrome found so far.
Step 2: The expand function
- It starts with two pointers,
landr. - While both are inside the string and
s[l] === s[r], it moves them outward. - The loop stops after one extra step, so we return
[l + 1, r - 1]. - For an even center with different characters, like
expand(i, i + 1)on"ab", the loop does not run. We return[i + 1, i], which is an empty range, and it never wins.
Step 3: Try every center
- For each index
i, we try the odd center and the even center. - If a range is longer than the best one, we save it.
Step 4: Return the answer
s.slice(start, end + 1)gives the substring.
Dry Run
Let us take s = "babad".
i | Center | Palindrome found | Best so far |
|---|---|---|---|
0 | b | b | b |
0 | ba | none | b |
1 | a | bab | bab |
1 | ab | none | bab |
2 | b | aba | bab (same length, so no change) |
2 | ba | none | bab |
3 | a | a | bab |
4 | d | d | bab |
The answer is "bab".
Complexity
- Time Complexity:
O(n²)- There are
2n - 1centers. - Each expansion takes up to
O(n).
- There are
- Space Complexity:
O(1)- We use only a few variables. The output string is not counted.
Comparison
| Approach | Time Complexity | Space Complexity |
|---|---|---|
| Brute Force | O(n³) | O(1) |
| Expand Around Center | O(n²) | O(1) |
Summary
- Every palindrome has a center, so we grow outward from each center.
- There are two center types: one
Can We Do Better? Manacher's Algorithm
Expand Around Center repeats work. When we move from one center to the next, we throw away what we learned. Manacher's algorithm reuses it, and finds the longest palindrome in O(n) time.
Step 1: Remove the odd/even problem
Odd and even palindromes have different centers. We fix this by putting a separator (#) between all characters, and at both ends.
s = "abba" -> t = "#a#b#b#a#"
s = "aba" -> t = "#a#b#a#"
Now every palindrome in t has odd length, and its center is a single character. So we need only one kind of center.
Step 2: Store the palindrome size at every center
We build an array p. The value p[i] is the radius of the longest palindrome centered at index i in t. It is the number of characters we can step to each side.
- A radius of
p[i]intmeans a palindrome of lengthp[i]in the original string.
Step 3: Reuse the old result with a mirror
We keep the palindrome that reaches farthest right so far. It has a center center and a right edge right.
For a new index i:
- If
i < right, theniis inside that big palindrome. - Its mirror is
mirror = 2 * center - i. The palindrome aroundilooks like the one aroundmirror, because the big palindrome is symmetric. - So we start with
p[i] = min(right - i, p[mirror]). We take themin, because the mirror's palindrome may go outside the big one, and we cannot trust anything beyondright. - Then we try to expand more from there.
- If the new palindrome goes past
right, we updatecenterandright.
Code
var longestPalindrome = function (s) {
// add separators, so every palindrome has odd length
const t = "#" + s.split("").join("#") + "#";
const n = t.length;
const p = new Array(n).fill(0);
let center = 0; // center of the palindrome that reaches farthest right
let right = 0; // right edge of that palindrome
let bestLen = 0;
let bestCenter = 0;
for (let i = 0; i < n; i++) {
// reuse the answer from the mirror position
if (i < right) {
const mirror = 2 * center - i;
p[i] = Math.min(right - i, p[mirror]);
}
// try to expand more
while (
i - p[i] - 1 >= 0 &&
i + p[i] + 1 < n &&
t[i - p[i] - 1] === t[i + p[i] + 1]
) {
p[i]++;
}
// this palindrome reaches farther right, so remember it
if (i + p[i] > right) {
center = i;
right = i + p[i];
}
// keep the longest palindrome
if (p[i] > bestLen) {
bestLen = p[i];
bestCenter = i;
}
}
// convert the position in t back to a position in s
const start = Math.floor((bestCenter - bestLen) / 2);
return s.slice(start, start + bestLen);
};
How the Code Works
t: The string with#added. For"babad", it is"#b#a#b#a#d#".p[i]: The radius of the palindrome ati. Int, this equals the length of that palindrome ins.- Mirror step: If
iis inside the farthest palindrome, we copy a safe starting value frommirror. We cap it withright - i. - Expand: The
whileloop grows the palindrome. It checks the characters just outside the current radius. - Update: If the palindrome passes
right, it becomes the new farthest palindrome. - Convert back: A palindrome of length
bestLencentered atbestCenterintstarts at(bestCenter - bestLen) / 2ins.
Dry Run
Let us take s = "abba". Then t = "#a#b#b#a#", with indexes 0 to 8.
i | t[i] | Start of p[i] | After expanding p[i] | Palindrome in t | center, right |
|---|---|---|---|---|---|
0 | # | 0 | 0 | # | 0, 0 |
1 | a | 0 | 1 | #a# | 1, 2 |
2 | # | min(0, p[0]) = 0 | 0 | # | 1, 2 |
3 | b | 0 | 1 | #b# | 3, 4 |
4 | # | 0 | 4 | #a#b#b#a# | 4, 8 |
5 | b | min(3, p[3]) = 1 | 1 | #b# | 4, 8 |
6 | # | min(2, p[2]) = 0 | 0 | # | 4, 8 |
7 | a | min(1, p[1]) = 1 | 1 | #a# | 4, 8 |
8 | # | min(0, p[0]) = 0 | 0 | # | 4, 8 |
- The biggest radius is
p[4] = 4, sobestLen = 4andbestCenter = 4. start = (4 - 4) / 2 = 0.- The answer is
s.slice(0, 4) = "abba".
Why It Is O(n)
- The pointer
rightonly moves forward. It never goes back. - A
whileloop step happens only when we passright. So the total number of expansion steps over the whole run is at most the length oft. - The mirror step costs
O(1).
So the total work is O(n).
Complexity
- Time Complexity:
O(n)thas2n + 1characters, and each one is handled in amortizedO(1)time.
- Space Complexity:
O(n)- The string
tand the arraypboth have about2nentries.
- The string
Updated Comparison
| Approach | Time Complexity | Space Complexity |
|---|---|---|
| Brute Force | O(n³) | O(1) |
| Expand Around Center | O(n²) | O(1) |
| Dynamic Programming (table) | O(n²) | O(n²) |
| Manacher's Algorithm | O(n) | O(n) |
Should You Use It?
- For this problem,
n <= 1000. SoO(n²)is already fast, and Expand Around Center is the best choice for an interview. It is short and easy to explain. - Manacher's algorithm is the answer to "can you do it in linear time?". It trades extra memory and harder code for better speed.
- If the string were much longer, for example
10^6characters, Manacher's would be the right choice.
Updated Summary
- Expand Around Center runs in
O(n²)time andO(1)space. - Manacher's algorithm makes it
O(n)by reusing results from the mirror position inside the farthest palindrome. - The
#separators turn all palindromes into odd length, so we handle one kind of center. - The pointer
rightnever moves back, so the total work is linear. - The trade is
O(n)extra space forO(n)time.