AlgoTales · Roadmap

Palindromic subsequence

Advanced · 10 min · code in PHP, JavaScript, Java and Go

Where you will meet this in real life

The longest palindromic subsequence is the longest sequence of letters in a string, picked in order with gaps allowed, that reads the same backwards and forwards. You compare the two ends and shrink inwards. It also tells you how few letters to add to turn a string into a palindrome.

Practical use cases

  • Web app: Making a password or code symmetrical. A promo-code generator wants codes that look pleasantly symmetrical, so it takes a user's word and works out the fewest letters to insert to make it a palindrome. The answer is the length of the word minus its longest palindromic subsequence, and the app shows the finished code.
  • Web app: Word puzzle hint. A word-game site shows the longest mirror pattern hidden in a player's rack of letters as a hint. The table method finds it for a 12-letter rack in a blink. Players who ask for a hint get a nudge toward the mirror pattern without the app revealing a full word, which keeps the game fun and fair.
  • System: DNA hairpins and compression. Some DNA strands fold back on themselves where the sequence mirrors, and finding these stretches helps biologists predict shapes. Biologists use these mirrored stretches to predict how a strand will bend, and the table finds them in a fraction of a second even for long strands.

The story: The Mirror Necklace

Grandpa Bhaskar showed Mira a string of beads lettered A G B C B A. "Remove as many beads as you like (keeping the order of the rest) so that what remains reads the same forwards and backwards. What is the longest necklace you can keep?"

Mira put a finger on each end. If the two end beads are the same, they can be the two ends of the mirror, so keep both and solve the inside. If they are different, one of them has to go: throw away the left one or the right one, and take whichever leaves the better necklace.

The "inside" is always a smaller stretch of the same beads, so Mira filled a table of stretches: all length-1 stretches first (each worth 1), then length 2, then 3, until the whole string. The answer was 5 (A B C B A, dropping only the G). This is the Longest Palindromic Subsequence, our first table filled by stretch length instead of row by row.

How to spot this problem, and where you need it

You need the longest mirror-like sequence hidden inside a string, or the fewest changes to make a string read the same backwards, when letters may be skipped.

Signs you need it

  • The problem says "longest palindromic subsequence" or "minimum insertions to make a palindrome".
  • Letters at both ends of a range either match, which lets you shrink inwards, or do not.
  • A solution that tries all subsequences is far too slow beyond 20 or so letters.

Where to use it in a project

  • Text and word-game features that need hidden symmetry or mirror patterns.
  • Generating or validating symmetrical codes, names or identifiers.

The solution

Use a table indexed by a start and an end position. A single letter has a result of 1. For a range, if the first and last letters match, the answer is 2 plus the answer for the range inside them. If they differ, take the larger of the answers when dropping the first letter or dropping the last. Fill from short ranges to long ones. The cell for the whole string is the answer.

Payoff: Before: checking about a million subsequences for 20 letters. After: a table of 400 cells.

Explain it like I am 8

Imagine a row of beads and you hold one finger on each end. If the two end beads match, you keep them and look at the beads between. If not, you throw one end away and try again. You write down the answers for short stretches first so longer stretches can peek at them.

How it works, step by step

  1. One letter is a palindrome of length 1: dp[i][i] = 1.
  2. Fill the table by stretch length 2, 3, 4... so inner stretches are always ready.
  3. If s[i] equals s[j]: dp[i][j] = dp[i+1][j-1] + 2 (keep both ends; an empty inside is 0).
  4. Otherwise: dp[i][j] = max(dp[i+1][j], dp[i][j-1]).
  5. The answer is dp[0][n-1], the stretch that is the whole word.

The code in four languages

PHP

<?php
// Length of the longest palindromic subsequence of $s.
function longestPalSubseq(string $s): int {
    $n = strlen($s);
    $dp = array_fill(0, $n, array_fill(0, $n, 0));
    for ($i = $n - 1; $i >= 0; $i--) {          // start from the right so inner stretches are done
        $dp[$i][$i] = 1;                         // a single letter
        for ($j = $i + 1; $j < $n; $j++) {
            if ($s[$i] === $s[$j]) {
                $dp[$i][$j] = $dp[$i + 1][$j - 1] + 2;               // keep both ends
            } else {
                $dp[$i][$j] = max($dp[$i + 1][$j], $dp[$i][$j - 1]);  // drop one end
            }
        }
    }
    return $dp[0][$n - 1];
}
echo longestPalSubseq('AGBCBA'), "\n";          // 5
echo longestPalSubseq('BBABCBCAB'), "\n";       // 7

JavaScript

// Length of the longest palindromic subsequence of s.
function longestPalSubseq(s) {
  const n = s.length;
  const dp = Array.from({ length: n }, () => new Array(n).fill(0));
  for (let i = n - 1; i >= 0; i--) {            // start from the right so inner stretches are done
    dp[i][i] = 1;                               // a single letter
    for (let j = i + 1; j < n; j++) {
      if (s[i] === s[j]) {
        dp[i][j] = dp[i + 1][j - 1] + 2;                      // keep both ends
      } else {
        dp[i][j] = Math.max(dp[i + 1][j], dp[i][j - 1]);      // drop one end
      }
    }
  }
  return dp[0][n - 1];
}
console.log(longestPalSubseq('AGBCBA'));        // 5
console.log(longestPalSubseq('BBABCBCAB'));     // 7

Java

public class Main {
    // Length of the longest palindromic subsequence of s.
    static int longestPalSubseq(String s) {
        int n = s.length();
        int[][] dp = new int[n][n];
        for (int i = n - 1; i >= 0; i--) {          // start from the right so inner stretches are done
            dp[i][i] = 1;                            // a single letter
            for (int j = i + 1; j < n; j++) {
                if (s.charAt(i) == s.charAt(j)) {
                    dp[i][j] = dp[i + 1][j - 1] + 2;                       // keep both ends
                } else {
                    dp[i][j] = Math.max(dp[i + 1][j], dp[i][j - 1]);       // drop one end
                }
            }
        }
        return dp[0][n - 1];
    }

    public static void main(String[] args) {
        System.out.println(longestPalSubseq("AGBCBA"));        // 5
        System.out.println(longestPalSubseq("BBABCBCAB"));     // 7
    }
}

Go

package main

import "fmt"

// Length of the longest palindromic subsequence of s.
func longestPalSubseq(s string) int {
	n := len(s)
	dp := make([][]int, n)
	for i := range dp {
		dp[i] = make([]int, n)
	}
	for i := n - 1; i >= 0; i-- { // start from the right so inner stretches are done
		dp[i][i] = 1 // a single letter
		for j := i + 1; j < n; j++ {
			if s[i] == s[j] {
				dp[i][j] = dp[i+1][j-1] + 2 // keep both ends
			} else {
				dp[i][j] = max(dp[i+1][j], dp[i][j-1]) // drop one end
			}
		}
	}
	return dp[0][n-1]
}

func main() {
	fmt.Println(longestPalSubseq("AGBCBA"))    // 5
	fmt.Println(longestPalSubseq("BBABCBCAB")) // 7
}

Time: O(n²) · Extra space: O(n²). One cell per start/end pair, each looking at its neighbours.

Watch out for

  • Confusing it with the longest palindromic substring, which must be unbroken.
  • Filling in the wrong order: the inside stretch dp[i+1][j-1] must be ready first.
  • Forgetting the inside is empty when the stretch has length 2: it contributes 0, not garbage.

Quick check

  1. If the two end letters match, what do we do?
    • Add 2 to the inside answer
    • Take the max of the two sides
    • Reset to 1
  2. What is the answer for a single letter?
    • 0
    • 1
    • 2
  3. Longest palindromic subsequence of AGBCBA?
    • 3
    • 6
    • 5