LeetCode #1143 Medium

Longest Common Subsequence

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.
dpstring
Open on LeetCode ↗
02

Intuition

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.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def longestCommonSubsequence(self, text1: str, text2: str) -> int:
▶3 m, n = len(text1), len(text2)
▶4 dp = [[0] * (n + 1) for _ in range(m + 1)]
▶5 for i in range(1, m + 1):
▶6 for j in range(1, n + 1):
▶7 if text1[i - 1] == text2[j - 1]:
▶8 dp[i][j] = dp[i - 1][j - 1] + 1
▶9 else:
▶10 dp[i][j] = max(dp[i - 1][j], dp[i][j - 1])
▶11 return dp[m][n]
ace0000a0b0c0d0e0this cellnot startedcommon subsequenceempty prefixes share nothing → 0
rows6first 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.
ace0000a01b0c0d0e0this cell0diagonal+1pair=1newcommon subsequence'a' = 'a' → keep the pair, the diagonal grows to 1
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.
ace0000a011b0c0d0e0this cell0above1left→1largercommon subsequence'a' ≠ 'c' → drop one letter, keep 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.
ace0000a0111b0c0d0e0this cell0above1left→1largercommon subsequence'a' ≠ 'e' → drop one letter, keep 1
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.
ace0000a0111b01c0d0e0this cell1above0left→1largercommon subsequence'b' ≠ 'a' → drop one letter, keep 1
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.
ace0000a0111b011c0d0e0this cell1above1left→1largercommon subsequence'b' ≠ 'c' → drop one letter, keep 1
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.
ace0000a0111b0111c0d0e0this cell1above1left→1largercommon subsequence'b' ≠ 'e' → drop one letter, keep 1
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.
ace0000a0111b0111c01d0e0this cell1above0left→1largercommon subsequence'c' ≠ 'a' → drop one letter, keep 1
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.
ace0000a0111b0111c012d0e0this cell1diagonal+1pair=2newcommon subsequence'c' = 'c' → keep the pair, the diagonal grows to 2
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.
ace0000a0111b0111c0122d0e0this cell1above2left→2largercommon subsequence'c' ≠ 'e' → drop one letter, keep 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.
ace0000a0111b0111c0122d01e0this cell1above0left→1largercommon subsequence'd' ≠ 'a' → drop one letter, keep 1
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.
ace0000a0111b0111c0122d012e0this cell2above1left→2largercommon subsequence'd' ≠ 'c' → drop one letter, keep 2
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.
ace0000a0111b0111c0122d0122e0this cell2above2left→2largercommon subsequence'd' ≠ 'e' → drop one letter, keep 2
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.
ace0000a0111b0111c0122d0122e01this cell1above0left→1largercommon subsequence'e' ≠ 'a' → drop one letter, keep 1
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.
ace0000a0111b0111c0122d0122e012this cell2above1left→2largercommon subsequence'e' ≠ 'c' → drop one letter, keep 2
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.
ace0000a0111b0111c0122d0122e0123this cell2diagonal+1pair=3newcommon subsequence'e' = 'e' → keep the pair, the diagonal grows to 3
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.
ace0000a0111b0111c0122d0122e0123this cellreading backcommon subsequencee'e' matches → it is in the answer, go diagonally
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.
ace0000a0111b0111c0122d0122e0123this cellreading backcommon subsequencee'd' ≠ 'c' → the 2 came from above, go up
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.
ace0000a0111b0111c0122d0122e0123this cellreading backcommon subsequencece'c' matches → it is in the answer, go diagonally
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.
ace0000a0111b0111c0122d0122e0123this cellreading backcommon subsequencece'b' ≠ 'a' → the 1 came from above, go up
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.
ace0000a0111b0111c0122d0122e0123this cellreading backcommon subsequenceace'a' matches → it is in the answer, go diagonally
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.
ace0000a0111b0111c0122d0122e0123this cellfinishedcommon subsequenceaceanswer: 3, for example "ace"
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.
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.