Skip to content
Longest Common Subsequence
step 1/5

Reading — step 1 of 5

Read

~1 min readEdit Distance

Longest Common Subsequence

Diff is fundamentally about finding the LONGEST COMMON SUBSEQUENCE (LCS) — same characters in the same order, but not necessarily contiguous.

A: "ABCBDAB"
B: "BDCAB"
LCS: "BCAB" or "BDAB" (length 4)

Once you have the LCS, the diff is:

  • DELETE = chars in A not in LCS
  • INSERT = chars in B not in LCS
  • KEEP = LCS chars

DP:

python

To recover the actual LCS sequence, backtrack through the DP table from dp[n][m].

Edit distance and LCS are related: edit_dist(a, b) = len(a) + len(b) - 2 * lcs(a, b) when only insertions/deletions are allowed (no substitutions).

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…