Every time you run git diff, ask a DNA sequencer to find how two genes diverged, or let a text editor highlight what changed between two versions of a file, a single algorithm is doing the heavy lifting: Longest Common Subsequence (LCS).
The question is almost childishly simple. Given two strings — say, ABCBDAB and BDCABA — what is the longest sequence of characters that appears in both, in the same relative order, without rearranging anything? You don't have to pick consecutive characters; you just can't swap them around. For those two strings the answer is BCBA or BCAB (length 4): four characters appear in both strings, left-to-right, in matching order.
The naive approach — try every subsequence of the first string and check it against the second — takes exponential time. But this problem was solved in 1974 when researchers discovered a beautiful table-filling trick. Today it runs in time (where m and n are the string lengths), fast enough that diff tools apply it to thousands of lines in milliseconds.
LCS sits in P: it is definitively easy. What makes it worth studying is how elegantly dynamic programming turns an exponential search into a polynomial one — and how the same idea echoes through bioinformatics, version control, and spelling correction.
Comments
Loading comments...