awelgorithms

LCS on two strings

Updated

dp[i][j] = LCS length of s[0..i) and t[0..j). If s[i-1]==t[j-1], dp[i][j]=dp[i-1][j-1]+1. Else max(dp[i-1][j], dp[i][j-1]). Bases: i=0 or j=0 is 0.

What to focus on

Carry both strings as s, t and as a = [s, t]. LCS is a subsequence, not a substring — letters may skip. Walking only the diagonal assumes the strings already match.

Worked examples

full ace inside

s = "ace", t = "abcde", a = ["ace", "abcde"]
  1. match a, skip b, match c, skip d, match e
  2. dp[3][5]=3

Result: 3

prefix ac vs abc

s = "ace", t = "abcde", a = ["ace", "abcde"], i = 2, j = 3
  1. s[0..2)=ac, t[0..3)=abc
  2. match a, skip b, match c

Result: dp[2][3]=2

empty s

s = "", t = "abcde", a = ["", "abcde"]
  1. i=0 row is 0

Result: 0

Try it

Write lcs(s, t). s and t are strings of lowercase letters. dp[i][j] is LCS length of s[0..i) and t[0..j). Fill the table. Return dp[n][m]. Empty s against t is 0. dp[3][5] for s="ace" t="abcde" → 3. dp[2][3] → 2. LCS("", "abcde") → 0.

s and t are strings of lowercase letters. Empty s is in scope because it is an LCS base.