Why it matters

LCS is classic DP. Understanding shapes sequence problems.

Advertisement

The architecture

dp[i][j] = LCS length of s1[0..i], s2[0..j].

Match: dp[i-1][j-1] + 1.

Else: max(dp[i-1][j], dp[i][j-1]).

LCS DP transitionsMatchdp[i-1][j-1] + 1Skip s1dp[i-1][j]Skip s2dp[i][j-1]Hirschberg's algorithm reduces space to O(m+n) via divide-and-conquer
LCS.
Advertisement

How it works end to end

Backtrace for actual LCS.

Space O(min(m,n)) with rolling.

Hirschberg for O(m+n) space with backtrace.