~/DHRUVUpskilling
← board/DSA/Dynamic Programming/dsa-dynamic-programming-35
Backlog·queued

Longest palindromic Subsequence

DifficultyMedium
PatternDynamic Programming
TrackDSA
tl;dr

return longest palindrome

full write-up

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 <= 1000
  • s has 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 with l = i and r = i.
  • Even length: The center is between two characters, like "abba". We start with l = i and r = 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 to O(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

  • start and end hold the range of the longest palindrome found so far.

Step 2: The expand function

  • It starts with two pointers, l and r.
  • 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".

iCenterPalindrome foundBest so far
0bbb
0banoneb
1ababbab
1abnonebab
2bababab (same length, so no change)
2banonebab
3aabab
4ddbab

The answer is "bab".

Complexity

  • Time Complexity: O(n²)
    • There are 2n - 1 centers.
    • Each expansion takes up to O(n).
  • Space Complexity: O(1)
    • We use only a few variables. The output string is not counted.

Comparison

ApproachTime ComplexitySpace Complexity
Brute ForceO(n³)O(1)
Expand Around CenterO(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] in t means a palindrome of length p[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, then i is inside that big palindrome.
  • Its mirror is mirror = 2 * center - i. The palindrome around i looks like the one around mirror, because the big palindrome is symmetric.
  • So we start with p[i] = min(right - i, p[mirror]). We take the min, because the mirror's palindrome may go outside the big one, and we cannot trust anything beyond right.
  • Then we try to expand more from there.
  • If the new palindrome goes past right, we update center and right.

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 at i. In t, this equals the length of that palindrome in s.
  • Mirror step: If i is inside the farthest palindrome, we copy a safe starting value from mirror. We cap it with right - i.
  • Expand: The while loop 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 bestLen centered at bestCenter in t starts at (bestCenter - bestLen) / 2 in s.

Dry Run

Let us take s = "abba". Then t = "#a#b#b#a#", with indexes 0 to 8.

it[i]Start of p[i]After expanding p[i]Palindrome in tcenter, right
0#00#0, 0
1a01#a#1, 2
2#min(0, p[0]) = 00#1, 2
3b01#b#3, 4
4#04#a#b#b#a#4, 8
5bmin(3, p[3]) = 11#b#4, 8
6#min(2, p[2]) = 00#4, 8
7amin(1, p[1]) = 11#a#4, 8
8#min(0, p[0]) = 00#4, 8
  • The biggest radius is p[4] = 4, so bestLen = 4 and bestCenter = 4.
  • start = (4 - 4) / 2 = 0.
  • The answer is s.slice(0, 4) = "abba".

Why It Is O(n)

  • The pointer right only moves forward. It never goes back.
  • A while loop step happens only when we pass right. So the total number of expansion steps over the whole run is at most the length of t.
  • The mirror step costs O(1).

So the total work is O(n).

Complexity

  • Time Complexity: O(n)
    • t has 2n + 1 characters, and each one is handled in amortized O(1) time.
  • Space Complexity: O(n)
    • The string t and the array p both have about 2n entries.

Updated Comparison

ApproachTime ComplexitySpace Complexity
Brute ForceO(n³)O(1)
Expand Around CenterO(n²)O(1)
Dynamic Programming (table)O(n²)O(n²)
Manacher's AlgorithmO(n)O(n)

Should You Use It?

  • For this problem, n <= 1000. So O(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^6 characters, Manacher's would be the right choice.

Updated Summary

  • Expand Around Center runs in O(n²) time and O(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 right never moves back, so the total work is linear.
  • The trade is O(n) extra space for O(n) time.
Longest palindromic Subsequence — pattern notes — Dhruv Parmar