← Back to Algorithms, page 5

algorithms-0087 · Hard senior

Longest palindromic subsequence: find the length of the longest subsequence that reads the same forwards and backwards, and use it to get the minimum insertions that make a string a palindrome.

Let dp[i][j] be the answer for s[i..j]. If s[i] == s[j], dp[i][j] = dp[i+1][j-1] + 2; otherwise dp[i][j] = max(dp[i+1][j], dp[i][j-1]). Filling i from the end and j forward takes O(n^2) time, and one row with a saved diagonal gives O(n) space. It also equals the LCS of s and its reverse, and the minimum insertions is n minus this length.

Full answer

Problem

Given a string s, return the length of its longest palindromic subsequence (characters keep their order but need not be adjacent). Then return the minimum number of insertions to make s a palindrome.

Example: "bbbab" gives 4 (bbbb); "cbbd" gives 2 (bb). "mbadm" needs 2 insertions (for example mbdadbm).

Constraints: 1 <= len(s) <= 1,000. Note that this differs from the longest palindromic substring, which must be contiguous.

Brute force

Check every subsequence, longest first, for being a palindrome: O(2^n * n).

Optimal approach

Interval DP over s[i..j]:

  • dp[i][i] = 1.
  • If s[i] == s[j]: dp[i][j] = dp[i+1][j-1] + 2.
  • Else: dp[i][j] = max(dp[i+1][j], dp[i][j-1]).

Fill i from n - 1 down to 0 and j from i + 1 up to n - 1 so that dp[i+1][*] is ready. To save space, keep one row and a diag variable holding dp[i+1][j-1] before it is overwritten.

Minimum insertions = n - LPS, because the characters outside the palindromic subsequence each need a mirror inserted.

Why it works

If the end characters match, some longest palindromic subsequence uses both of them as its outer pair (swapping them in never hurts), leaving the inside. If they differ, they cannot both be the outer pair, so at least one end is unused and the answer comes from dropping one end. Each case reduces to a shorter interval, so filling by increasing length covers all dependencies.

Complexity

O(n^2) time; O(n) space with one rolling row (O(n^2) if the subsequence itself must be rebuilt).

Code

python
import random
from itertools import combinations


def lps(s):
    """Longest palindromic subsequence (characters need not be contiguous).
    dp[i][j] over s[i..j]; rolled to one row. O(n^2) time, O(n) space."""
    n = len(s)
    if n == 0:
        return 0
    dp = [0] * n                          # dp[j] holds the value for the current i
    for i in range(n - 1, -1, -1):
        dp[i] = 1
        diag = 0                          # dp[i+1][j-1] from the previous row
        for j in range(i + 1, n):
            keep = dp[j]                  # dp[i+1][j] before overwrite
            if s[i] == s[j]:
                dp[j] = diag + 2
            else:
                dp[j] = max(dp[j], dp[j - 1])
            diag = keep
    return dp[n - 1]


def lps_via_lcs(s):
    """Equivalent: LCS of s and reversed s."""
    t = s[::-1]
    prev = [0] * (len(t) + 1)
    for a in s:
        cur = [0]
        for j, b in enumerate(t, 1):
            cur.append(prev[j - 1] + 1 if a == b else max(prev[j], cur[-1]))
        prev = cur
    return prev[-1]


def min_insertions_to_palindrome(s):
    return len(s) - lps(s)


def brute(s):
    for k in range(len(s), 0, -1):
        for idx in combinations(range(len(s)), k):
            sub = "".join(s[i] for i in idx)
            if sub == sub[::-1]:
                return k
    return 0


if __name__ == "__main__":
    assert lps("bbbab") == 4                            # bbbb
    assert lps("cbbd") == 2
    assert lps("") == 0 and lps("a") == 1
    assert min_insertions_to_palindrome("mbadm") == 2
    rng = random.Random(87)
    for _ in range(600):
        s = "".join(rng.choice("abc") for _ in range(rng.randint(0, 10)))
        assert lps(s) == lps_via_lcs(s) == brute(s)
    print("all tests passed")

Save as b87_longest_palindromic_subsequence.py and run python3 b87_longest_palindromic_subsequence.py. It prints all tests passed (Python 3.13.5).

Edge cases

Empty string (0). One character (1). All characters the same (n). All different (1). Do not confuse it with the substring problem, which uses expand-around-center and answers 3 for "bbbab" (bbb or bab) instead of 4.

Pattern

Interval DP on s[i..j], filled by increasing interval length or decreasing i. The same structure solves palindrome partitioning (minimum cuts), burst balloons, matrix chain multiplication and optimal game strategy on a row of coins. The LCS-with-reverse identity is a useful second derivation in interviews.

python
import random
from itertools import combinations


def lps(s):
    """Longest palindromic subsequence (characters need not be contiguous).
    dp[i][j] over s[i..j]; rolled to one row. O(n^2) time, O(n) space."""
    n = len(s)
    if n == 0:
        return 0
    dp = [0] * n                          # dp[j] holds the value for the current i
    for i in range(n - 1, -1, -1):
        dp[i] = 1
        diag = 0                          # dp[i+1][j-1] from the previous row
        for j in range(i + 1, n):
            keep = dp[j]                  # dp[i+1][j] before overwrite
            if s[i] == s[j]:
                dp[j] = diag + 2
            else:
                dp[j] = max(dp[j], dp[j - 1])
            diag = keep
    return dp[n - 1]


def lps_via_lcs(s):
    """Equivalent: LCS of s and reversed s."""
    t = s[::-1]
    prev = [0] * (len(t) + 1)
    for a in s:
        cur = [0]
        for j, b in enumerate(t, 1):
            cur.append(prev[j - 1] + 1 if a == b else max(prev[j], cur[-1]))
        prev = cur
    return prev[-1]


def min_insertions_to_palindrome(s):
    return len(s) - lps(s)


def brute(s):
    for k in range(len(s), 0, -1):
        for idx in combinations(range(len(s)), k):
            sub = "".join(s[i] for i in idx)
            if sub == sub[::-1]:
                return k
    return 0


if __name__ == "__main__":
    assert lps("bbbab") == 4                            # bbbb
    assert lps("cbbd") == 2
    assert lps("") == 0 and lps("a") == 1
    assert min_insertions_to_palindrome("mbadm") == 2
    rng = random.Random(87)
    for _ in range(600):
        s = "".join(rng.choice("abc") for _ in range(rng.randint(0, 10)))
        assert lps(s) == lps_via_lcs(s) == brute(s)
    print("all tests passed")

One-row interval DP with a saved diagonal, the LCS-with-reverse equivalent, minimum insertions, and an exhaustive subsequence check on random strings.

Complexity

Time: O(n^2). Space: O(n). Rebuilding the actual subsequence needs the full O(n^2) table or a second pass.

By level

Fresher: Writes the 2D interval table for small strings and explains the matching-ends case. Distinguishes the problem from the substring version.

Mid: Compresses to one row with a saved diagonal, derives minimum insertions, and explains the LCS equivalence. Rebuilds the subsequence from the full table.

Senior: Places the problem in the interval DP family and explains how fill order follows from dependencies. Discusses memory limits for long strings and when an O(n^2) table is too large.

Key points

  • Matching ends add 2 to the inside
  • Otherwise drop one end
  • Fill i downward, j upward
  • Equals LCS(s, reverse(s))
  • Insertions = n - LPS

Common mistakes

  • Confusing subsequence with substring
  • Wrong fill order so dp[i+1] is not ready
  • Losing the diagonal value in the rolling row
  • Off-by-one for intervals of length 2

Follow-ups

  • How would you rebuild the palindrome itself?
  • How do you find the minimum deletions instead of insertions?
  • How would you count distinct palindromic subsequences?

Tips

  • Clarify subsequence versus substring first
  • Explain the fill order
  • Mention the LCS identity

Evaluation rubric

  • Correct recurrence
  • Correct fill order
  • Space optimization
  • Connects to insertions