Longest Common Subsequence is LeetCode 1143 (Medium). You get two strings, text1 and text2. Return the length of their LCS, the longest string that is a subsequence of both, or 0 if they share no letter.
A subsequence keeps the original order of the letters but may skip any of them. A common subsequence is one you can get from both strings by deleting letters.
Constraints
1 <= text1.length, text2.length <= 1000
text1 and text2 consist of only lowercase English characters.
There are 2ⁿ subsequences of a string, so listing them is hopeless. Instead, ask about prefixes: what is the answer for the first i letters of text1 and the first j letters of text2? Only the last letter of each prefix needs a decision.
Last letters equal: keep the pair. Some best answer always ends with it, so the answer is one more than for both shorter prefixes.
Last letters differ: they cannot both be used, so drop one of them. You do not know which, so try both and keep the larger.
That gives one cell per prefix pair, each filled from three neighbours, which is the LCS algorithm.
03
Approach
1
Make a table with an empty row and column
Create dp with m + 1 rows and n + 1 columns, all zeros. Row 0 and column 0 stand for an empty prefix, which shares nothing with anything, so the zeros there are already correct.
2
Fill each cell from its neighbours
For row i and column j, compare text1[i-1] with text2[j-1].
Equal: dp[i][j] = dp[i-1][j-1] + 1 (the diagonal, plus this pair).
Different: dp[i][j] = max(dp[i-1][j], dp[i][j-1]) (drop a letter from one string).
Going row by row, left to right, means all three neighbours are ready.
3
Read the answer from the corner
dp[m][n] covers both whole strings, so it is the answer. Every other cell answers a smaller version of the same question.
4
Recover the letters by walking back
Start at the corner. When the two letters match, record the letter and step diagonally. Otherwise step to the neighbour, up or left, that holds the same value. Reverse the recorded letters to get one longest common subsequence.
5
Shrink to one row when only the length matters
Each row reads only the row above, so one array of n + 1 numbers is enough. Save the old diagonal value in a variable before you overwrite it, because the next cell to the right still needs it.
Row 0 and column 0 are the empty prefix. An empty string has no common subsequence with anything, so those cells start at 0. Every other cell will be built from cells above it and to its left, which is why the zeros are enough to get going.
prefixes"a" and "a"
value1
The last letters match, so this pair can finish a common subsequence. Taking it never hurts: whatever the shorter prefixes share (the diagonal, 0) plus this pair gives 1.
prefixes"a" and "ac"
value1
The last letters differ, so at most one of them can be used. Dropping 'a' leaves the cell above (0), dropping 'c' leaves the cell to the left (1). Nothing new is shared, so the cell takes the larger one, 1, and adds nothing.
prefixes"a" and "ace"
value1
The last letters differ, so at most one of them can be used. Dropping 'a' leaves the cell above (0), dropping 'e' leaves the cell to the left (1). Nothing new is shared, so the cell takes the larger one, 1, and adds nothing.
prefixes"ab" and "a"
value1
The last letters differ, so at most one of them can be used. Dropping 'b' leaves the cell above (1), dropping 'a' leaves the cell to the left (0). Nothing new is shared, so the cell takes the larger one, 1, and adds nothing.
prefixes"ab" and "ac"
value1
The last letters differ, so at most one of them can be used. Dropping 'b' leaves the cell above (1), dropping 'c' leaves the cell to the left (1). Nothing new is shared, so the cell takes the larger one, 1, and adds nothing.
prefixes"ab" and "ace"
value1
The last letters differ, so at most one of them can be used. Dropping 'b' leaves the cell above (1), dropping 'e' leaves the cell to the left (1). Nothing new is shared, so the cell takes the larger one, 1, and adds nothing.
prefixes"abc" and "a"
value1
The last letters differ, so at most one of them can be used. Dropping 'c' leaves the cell above (1), dropping 'a' leaves the cell to the left (0). Nothing new is shared, so the cell takes the larger one, 1, and adds nothing.
prefixes"abc" and "ac"
value2
The last letters match, so this pair can finish a common subsequence. Taking it never hurts: whatever the shorter prefixes share (the diagonal, 1) plus this pair gives 2.
prefixes"abc" and "ace"
value2
The last letters differ, so at most one of them can be used. Dropping 'c' leaves the cell above (1), dropping 'e' leaves the cell to the left (2). Nothing new is shared, so the cell takes the larger one, 2, and adds nothing.
prefixes"abcd" and "a"
value1
The last letters differ, so at most one of them can be used. Dropping 'd' leaves the cell above (1), dropping 'a' leaves the cell to the left (0). Nothing new is shared, so the cell takes the larger one, 1, and adds nothing.
prefixes"abcd" and "ac"
value2
The last letters differ, so at most one of them can be used. Dropping 'd' leaves the cell above (2), dropping 'c' leaves the cell to the left (1). Nothing new is shared, so the cell takes the larger one, 2, and adds nothing.
prefixes"abcd" and "ace"
value2
The last letters differ, so at most one of them can be used. Dropping 'd' leaves the cell above (2), dropping 'e' leaves the cell to the left (2). Nothing new is shared, so the cell takes the larger one, 2, and adds nothing.
prefixes"abcde" and "a"
value1
The last letters differ, so at most one of them can be used. Dropping 'e' leaves the cell above (1), dropping 'a' leaves the cell to the left (0). Nothing new is shared, so the cell takes the larger one, 1, and adds nothing.
prefixes"abcde" and "ac"
value2
The last letters differ, so at most one of them can be used. Dropping 'e' leaves the cell above (2), dropping 'c' leaves the cell to the left (1). Nothing new is shared, so the cell takes the larger one, 2, and adds nothing.
prefixes"abcde" and "ace"
value3
The last letters match, so this pair can finish a common subsequence. Taking it never hurts: whatever the shorter prefixes share (the diagonal, 2) plus this pair gives 3.
letters found1 of 3
Reading the letters back. The number alone does not say which letters are shared, but the table remembers how each cell was made. A matching pair means the letter is part of the answer; otherwise follow the neighbour that holds the same value, because that is where the number was copied from.
letters found1 of 3
Reading the letters back. The number alone does not say which letters are shared, but the table remembers how each cell was made. A matching pair means the letter is part of the answer; otherwise follow the neighbour that holds the same value, because that is where the number was copied from.
letters found2 of 3
Reading the letters back. The number alone does not say which letters are shared, but the table remembers how each cell was made. A matching pair means the letter is part of the answer; otherwise follow the neighbour that holds the same value, because that is where the number was copied from.
letters found2 of 3
Reading the letters back. The number alone does not say which letters are shared, but the table remembers how each cell was made. A matching pair means the letter is part of the answer; otherwise follow the neighbour that holds the same value, because that is where the number was copied from.
letters found3 of 3
Reading the letters back. The number alone does not say which letters are shared, but the table remembers how each cell was made. A matching pair means the letter is part of the answer; otherwise follow the neighbour that holds the same value, because that is where the number was copied from.
answer3bottom-right cell
one LCS"ace"
Answer 3. The bottom-right cell covers both whole strings. The walk back collected exactly 3 letters, one per green +1 cell on the path, so the letters and the number always agree.
rows3first i letters of text1
columns3first j letters of text2
Row 0 and column 0 are the empty prefix. An empty string has no common subsequence with anything, so those cells start at 0. Every other cell will be built from cells above it and to its left, which is why the zeros are enough to get going.
prefixes"a" and "b"
value0
The last letters differ, so at most one of them can be used. Dropping 'a' leaves the cell above (0), dropping 'b' leaves the cell to the left (0). Nothing new is shared, so the cell takes the larger one, 0, and adds nothing.
prefixes"a" and "ba"
value1
The last letters match, so this pair can finish a common subsequence. Taking it never hurts: whatever the shorter prefixes share (the diagonal, 0) plus this pair gives 1.
prefixes"ab" and "b"
value1
The last letters match, so this pair can finish a common subsequence. Taking it never hurts: whatever the shorter prefixes share (the diagonal, 0) plus this pair gives 1.
prefixes"ab" and "ba"
value1
The last letters differ, so at most one of them can be used. Dropping 'b' leaves the cell above (1), dropping 'a' leaves the cell to the left (1). Nothing new is shared, so the cell takes the larger one, 1, and adds nothing.
letters found0 of 1
Reading the letters back. The number alone does not say which letters are shared, but the table remembers how each cell was made. A matching pair means the letter is part of the answer; otherwise follow the neighbour that holds the same value, because that is where the number was copied from.
letters found1 of 1
Reading the letters back. The number alone does not say which letters are shared, but the table remembers how each cell was made. A matching pair means the letter is part of the answer; otherwise follow the neighbour that holds the same value, because that is where the number was copied from.
answer1bottom-right cell
one LCS"a"
Answer 1. The bottom-right cell covers both whole strings. The walk back collected exactly 1 letters, one per green +1 cell on the path, so the letters and the number always agree.
rows4first i letters of text1
columns4first j letters of text2
Row 0 and column 0 are the empty prefix. An empty string has no common subsequence with anything, so those cells start at 0. Every other cell will be built from cells above it and to its left, which is why the zeros are enough to get going.
prefixes"a" and "d"
value0
The last letters differ, so at most one of them can be used. Dropping 'a' leaves the cell above (0), dropping 'd' leaves the cell to the left (0). Nothing new is shared, so the cell takes the larger one, 0, and adds nothing.
prefixes"a" and "de"
value0
The last letters differ, so at most one of them can be used. Dropping 'a' leaves the cell above (0), dropping 'e' leaves the cell to the left (0). Nothing new is shared, so the cell takes the larger one, 0, and adds nothing.
prefixes"a" and "def"
value0
The last letters differ, so at most one of them can be used. Dropping 'a' leaves the cell above (0), dropping 'f' leaves the cell to the left (0). Nothing new is shared, so the cell takes the larger one, 0, and adds nothing.
prefixes"ab" and "d"
value0
The last letters differ, so at most one of them can be used. Dropping 'b' leaves the cell above (0), dropping 'd' leaves the cell to the left (0). Nothing new is shared, so the cell takes the larger one, 0, and adds nothing.
prefixes"ab" and "de"
value0
The last letters differ, so at most one of them can be used. Dropping 'b' leaves the cell above (0), dropping 'e' leaves the cell to the left (0). Nothing new is shared, so the cell takes the larger one, 0, and adds nothing.
prefixes"ab" and "def"
value0
The last letters differ, so at most one of them can be used. Dropping 'b' leaves the cell above (0), dropping 'f' leaves the cell to the left (0). Nothing new is shared, so the cell takes the larger one, 0, and adds nothing.
prefixes"abc" and "d"
value0
The last letters differ, so at most one of them can be used. Dropping 'c' leaves the cell above (0), dropping 'd' leaves the cell to the left (0). Nothing new is shared, so the cell takes the larger one, 0, and adds nothing.
prefixes"abc" and "de"
value0
The last letters differ, so at most one of them can be used. Dropping 'c' leaves the cell above (0), dropping 'e' leaves the cell to the left (0). Nothing new is shared, so the cell takes the larger one, 0, and adds nothing.
prefixes"abc" and "def"
value0
The last letters differ, so at most one of them can be used. Dropping 'c' leaves the cell above (0), dropping 'f' leaves the cell to the left (0). Nothing new is shared, so the cell takes the larger one, 0, and adds nothing.
answer0
Answer 0. No pair of letters ever matched, so no cell got a +1 and the corner is still 0. The table needs no special case for this: the mismatch rule alone keeps every cell at 0.
05
Common pitfalls
Comparing text1[i] instead of text1[i-1]
✗ Wrong
if text1[i] == text2[j]:
✓ Right
if text1[i - 1] == text2[j - 1]:
Row i means the first i letters, so the letter it adds sits at index i - 1. With text1 = "a" the loop reaches i = 1 and text1[1] raises an IndexError.
Adding 1 when the letters differ
✗ Wrong
dp[i][j] = 1 + max(dp[i - 1][j], dp[i][j - 1])
✓ Right
dp[i][j] = max(dp[i - 1][j], dp[i][j - 1])
Nothing new is shared on a mismatch, so the count must not grow. On "abc" and "def" the wrong line returns 5 instead of 0.
Losing the diagonal in the one-row version
✗ Wrong
if a == b:
row[j] = row[j - 1] + 1
✓ Right
if a == b:
row[j] = diag + 1
row[j - 1] has already been updated for the current row, so it is the left cell, not the diagonal. Keep the old row[j] in diag before each write. On "a" and "aa" the wrong line returns 2.
06
Edge cases
No shared letter, e.g. "abc" and "def"
Every cell takes the mismatch branch and stays 0, so the answer is 0 with no special case.
07
Complexity
Time
O(m·n)
Space
O(m·n)
One constant-time cell per pair of prefixes. A single row cuts space to O(n), but then the letters can no longer be read back.
08
Longest Common Subsequence FAQ
Is LCS the same as the longest common substring?
No. A substring must be one unbroken block, a subsequence may skip letters. For "abcde" and "abxde" the LCS is "abde" (length 4) but the longest common substring is only "ab" or "de" (length 2). The substring table resets a cell to 0 on a mismatch instead of taking the max of its neighbours.
How is LCS related to the longest palindromic subsequence?
A palindrome reads the same forwards and backwards, so any palindromic subsequence of s is also a subsequence of s reversed. Running LCS on s and its reverse therefore answers Longest Palindromic Subsequence: "bbbab" against "babbb" gives 4. That page fills a triangle of ranges directly, which needs about half the cells.
Where is the LCS algorithm used in practice?
File comparison tools such as diff and the line diffs in Git are built on it: the lines in the LCS are unchanged, and everything else is shown as added or removed. It is also used to align DNA and protein sequences.