Why it matters

LCS underlies Git diff. Understanding shapes how you think about text comparison.

Advertisement

The architecture

DP: dp[i][j] = length of LCS for prefixes of length i and j.

Transition: if chars match, dp[i-1][j-1]+1; else max(dp[i-1][j], dp[i][j-1]).

LCS DPMatchextend LCSNo matchcarry longerTrace backreconstruct LCSDiff algorithms find LCS then output additions/deletions around it
LCS calculation.
Advertisement

How it works end to end

Reconstruction: trace back through DP table to get actual LCS.

Space optimization: only need last row for length; full table for reconstruction.

Diff: LCS gives common lines; changes are non-LCS lines.