How similar are two strings? Version control tools compare files line by line, spell checkers look for close words, and biologists compare DNA. Two classic dynamic programming problems answer this. The longest common subsequence (LCS) finds the longest sequence of characters that appears in both strings in the same order, though not necessarily side by side. The edit distance counts the fewest single-character changes that turn one string into the other. This lesson builds both in C and shows the DP table so you can follow every step.
In this lesson you will learn
- The difference between a subsequence and a substring
- The LCS recurrence and its two-dimensional DP table
- Recovering the actual LCS by walking back through the table
- Edit (Levenshtein) distance with insert, delete and replace
- Saving memory by keeping only two rows
You should know dynamic programming and strings in C.
Longest Common Subsequence
#include <stdio.h>
#include <string.h>
#define MAX 32
/* dp[i][j] = length of the LCS of the first i chars of a and the first j chars of b */
static int dp[MAX + 1][MAX + 1];
static int lcs(const char *a, const char *b, char *out) {
int n = (int)strlen(a), m = (int)strlen(b);
for (int i = 0; i <= n; i++) dp[i][0] = 0;
for (int j = 0; j <= m; j++) dp[0][j] = 0;
for (int i = 1; i <= n; i++)
for (int j = 1; j <= m; j++)
if (a[i - 1] == b[j - 1])
dp[i][j] = dp[i - 1][j - 1] + 1; /* characters match: extend */
else
dp[i][j] = dp[i - 1][j] > dp[i][j - 1] ? dp[i - 1][j] : dp[i][j - 1];
/* Walk back from dp[n][m] to recover one LCS */
int len = dp[n][m], i = n, j = m;
out[len] = '\0';
while (i > 0 && j > 0) {
if (a[i - 1] == b[j - 1]) { out[--len] = a[i - 1]; i--; j--; }
else if (dp[i - 1][j] >= dp[i][j - 1]) i--;
else j--;
}
return dp[n][m];
}
int main(void) {
const char *a = "ABCBDAB", *b = "BDCABA";
char out[MAX + 1];
int len = lcs(a, b, out);
printf("LCS of %s and %s: length %d, e.g. \"%s\"\n\n", a, b, len, out);
/* Print the table so you can follow the recurrence */
int n = (int)strlen(a), m = (int)strlen(b);
printf(" -");
for (int j = 0; j < m; j++) printf(" %c", b[j]);
printf("\n");
for (int i = 0; i <= n; i++) {
printf(" %c", i ? a[i - 1] : '-');
for (int j = 0; j <= m; j++) printf(" %d", dp[i][j]);
printf("\n");
}
len = lcs("dhaka-sylhet", "dinajpur-sylhet", out);
printf("\nLCS of two route names: %d, \"%s\"\n", len, out);
return 0;
}
Output
LCS of ABCBDAB and BDCABA: length 4, e.g. "BCBA"
- B D C A B A
- 0 0 0 0 0 0 0
A 0 0 0 0 1 1 1
B 0 1 1 1 1 2 2
C 0 1 1 2 2 2 2
B 0 1 1 2 2 3 3
D 0 1 2 2 2 3 3
A 0 1 2 2 3 3 4
B 0 1 2 2 3 4 4
LCS of two route names: 9, "da-sylhet"
- A subsequence keeps characters in order but may skip some: “BCBA” is a subsequence of “ABCBDAB” (positions 2, 3, 4 and 6). A substring would have to be continuous.
dp[i][j]is the LCS length of the firsticharacters ofaand the firstjofb. Row 0 and column 0 are 0, because an empty string has nothing in common with anything.- If the last characters match, they can end a common subsequence:
dp[i][j] = dp[i-1][j-1] + 1. Otherwise, drop the last character of one string or the other and keep the better result. - The bottom-right cell holds the answer, 4. Filling the table takes O(n × m) time and memory.
- Walking back from the bottom-right cell recovers one LCS: on a match, take the character and move diagonally; otherwise move towards the larger neighbour. Several different LCSs can have the same length; this walk finds one of them.
Edit Distance
#include <stdio.h>
#include <string.h>
static int min3(int a, int b, int c) {
int m = a < b ? a : b;
return m < c ? m : c;
}
/* Edit (Levenshtein) distance: fewest inserts, deletes or replacements turning s into t */
static int edit_distance(const char *s, const char *t) {
int n = (int)strlen(s), m = (int)strlen(t);
int prev[64], cur[64]; /* two rows are enough: O(m) memory */
for (int j = 0; j <= m; j++) prev[j] = j; /* turning "" into t[0..j) needs j inserts */
for (int i = 1; i <= n; i++) {
cur[0] = i; /* turning s[0..i) into "" needs i deletes */
for (int j = 1; j <= m; j++) {
int cost = s[i - 1] == t[j - 1] ? 0 : 1;
cur[j] = min3(prev[j] + 1, /* delete s[i-1] */
cur[j - 1] + 1, /* insert t[j-1] */
prev[j - 1] + cost); /* replace, or keep if equal */
}
memcpy(prev, cur, sizeof(int) * (size_t)(m + 1));
}
return prev[m];
}
int main(void) {
const char *pairs[][2] = {
{"kitten", "sitting"}, {"sunday", "saturday"}, {"algorithm", "algorithm"},
{"", "abc"}, {"recieve", "receive"},
};
for (int i = 0; i < 5; i++)
printf("%-10s -> %-10s : %d\n", pairs[i][0], pairs[i][1], edit_distance(pairs[i][0], pairs[i][1]));
/* A tiny spell checker: suggest the closest dictionary word */
const char *dict[] = {"array", "stack", "queue", "graph", "heap", "tree"};
const char *typo = "grahp";
int best = 0;
for (int i = 1; i < 6; i++)
if (edit_distance(typo, dict[i]) < edit_distance(typo, dict[best])) best = i;
printf("did you mean \"%s\" instead of \"%s\"? (distance %d)\n",
dict[best], typo, edit_distance(typo, dict[best]));
return 0;
}
Output
kitten -> sitting : 3
sunday -> saturday : 3
algorithm -> algorithm : 0
-> abc : 3
recieve -> receive : 2
did you mean "graph" instead of "grahp"? (distance 2)
- Edit distance (also called Levenshtein distance) allows three operations, each costing 1: insert a character, delete a character, or replace one character with another.
- The first row and column are easy: turning a string into an empty one takes one delete per character, and the reverse takes one insert per character.
- For each cell, take the cheapest of: delete (the cell above + 1), insert (the cell to the left + 1), or replace (the diagonal + 1, or + 0 if the characters already match).
- “kitten” becomes “sitting” in 3 steps: replace k with s, replace e with i, insert g.
- Each row only needs the row above it, so the program keeps just two rows (
prevandcur), cutting memory from O(n × m) to O(m). - The tiny spell checker picks the dictionary word with the smallest distance to the typo.
LCS vs Edit Distance
| LCS | Edit distance | |
|---|---|---|
| Measures | What the strings share | How much they differ |
| On a match | dp[i-1][j-1] + 1 | dp[i-1][j-1] (free) |
| On a mismatch | max of up and left | 1 + min of up, left and diagonal |
| Time | O(n × m) | O(n × m) |
| Used in | diff tools, DNA comparison | spell checkers, fuzzy search |
Common Mistakes
- Confusing subsequence with substring. The longest common substring is a different problem with a different recurrence.
- Off-by-one indexing:
dphas one extra row and column, so comparea[i-1]withb[j-1]. - Using the two-row trick and then trying to rebuild the LCS; rebuilding needs the full table.
- Exponential recursion without memoization for long strings.
Practice Exercises
Exercise 1. Using LCS, find the fewest deletions needed to make two strings equal by only deleting characters.
Show answer
Delete everything that is not in the LCS: (n - L) + (m - L), where L is the LCS length. For “ABCBDAB” and “BDCABA” that is (7 − 4) + (6 − 4) = 5.
Exercise 2. What is the edit distance between “abc” and “cab”?
Show answer
2: insert c at the front (“cabc”), then delete the final c (“cab”).
Frequently Asked Questions
How do diff tools such as git diff use LCS?
They treat each line as one “character” and find a longest common subsequence of lines. Lines in the LCS are unchanged; the rest are shown as removed or added. Real tools use faster variants, such as Myers’ algorithm.
Can edit distance give different costs to different operations?
Yes. Replace the + 1 for each operation with its own cost, for example making a replacement cost 2. The same table works with weighted costs.
Summary
- LCS: extend on a match, otherwise take the larger of up and left.
- Edit distance: 1 + the cheapest of insert, delete and replace.
- Both fill an (n + 1) × (m + 1) table in O(n × m) time.
- Walk back through the table to recover the actual answer.
