← All Exercises
Line Diff via Longest Common Subsequence
advancedjavascript
Background
Line diffs power code review, patch files, and sync tools. The LCS formulation is the classic O(n*m) baseline that Myers diff optimizes.
Problem
Given old and new line arrays, compute their longest common subsequence and emit a diff script: a line present in both prints as two spaces plus the line, a removed old line prints as - plus the line, and an added new line prints as + plus the line. Output the LCS length and the script.
Input
A JSON object {"old": string[], "new": string[]} of distinct line sequences.Output
A JSON object {"lcs": number, "diff": string[]} where each entry is prefixed with " ", "- ", or "+ ".Sample tests
Sample 1
Input: {"old":["a","b","c","d"],"new":["a","x","c","d"]}Expected: {"lcs":3,"diff":[" a","- b","+ x"," c"," d"]}Sample 2
Input: {"old":["1","2"],"new":["1","2","3","4"]}Expected: {"lcs":2,"diff":[" 1"," 2","+ 3","+ 4"]}Sample 3
Input: {"old":["x"],"new":["y"]}Expected: {"lcs":0,"diff":["- x","+ y"]}Your solution
Learning objective
Implement the LCS diff and walk the DP table deterministically.