Longest Palindromic Subsequence
A subsequence is palindromic if it is the same whether read left to right or right to left. For instance, in the sequence A, C, G, T, G, T, C, A, A, A, A, T, C, G, the subsequences A, C, G, C, A and A, A, A, A are palindromic, while A, C, T is not. Devise an algorithm that takes a sequence x[1…n] and returns the length of the longest palindromic subsequence.
This is a window problem: the table is indexed by both endpoints of a sub-range, and entries depend on strictly smaller windows. That's the tell for a 2-D interval table.
If the two ends match, they wrap a palindrome of the inside plus 2. If not, drop one end or the other and take the better. The T(i,i-1)=0 base case is what keeps the even-length case well-defined.
Entries depend on shorter windows, so fill by increasing window length ℓ = j − i (or decreasing i with increasing j). If asked for pseudocode, an outer loop over length and inner over start index is the clean way to guarantee dependencies are ready.
Optional pseudocode not required by Ed #9
A mechanical translation. Note the outer loop is over window length — that's what guarantees smaller windows are filled first.
function LongestPalinSubseq(x[1..n]): for i = 1 to n: T[i][i] = 1 for i = 2 to n: T[i][i-1] = 0 # empty windows for L = 1 to n-1: # window length for i = 1 to n-L: j = i + L if x[i] == x[j]: T[i][j] = 2 + T[i+1][j-1] else: T[i][j] = max(T[i+1][j], T[i][j-1]) return T[1][n]
Try it yourself
worked example + self-testMatch ends → 2+T(i+1,j−1); else max{T(i+1,j), T(i,j−1)}. Fill by window length.
x = A G C T G A (n = 6)
A G T G A.x = B B A B C B C A B (n = 9)
Reveal answer
B A C B C A B (also B B C B C B B).