Longest Common Subsequence
Your code isn't saved yet: refreshing or leaving the page resets it. Saved progress comes with user accounts.
Given two strings text1 and text2, return the length of their longest common subsequence. If there is none, return 0.
Understand the problem
- A subsequence keeps some characters in their original order, but not necessarily next to each other:
"ace"is a subsequence of"abcde"(skipbandd)."aec"is not (wrong order). - A common subsequence is a subsequence of both strings.
- You want the length of the longest one.
Example 1
Input: text1 = "abcde", text2 = "ace"
Output: 3"ace" is in both.
Example 2
Input: text1 = "abc", text2 = "abc"
Output: 3The whole string.
Example 3
Input: text1 = "abc", text2 = "def"
Output: 0No letters in common at all.
Constraints
1 <= text1.length, text2.length <= 1000- Both strings contain lowercase English letters.
Hints
Stuck? Open one hint at a time. Each one gives away a little more than the last.
The idea in one sentence
Compare the strings one character at a time: if the current characters match, count it and move both forward; if not, try skipping a character from either string and keep the better result, saving every answer in a 2-D table.
The naive approach (and why it's slow)
List every subsequence of text1 (there are 2^n of them) and check each against text2. With 1000 characters, that's impossible.
The key insight: compare the first characters
Let lcs[i][j] = the answer for the rest of the strings: text1 from position i, and text2 from position j. Look at the first character of each:
- They match (
text1[i] === text2[j]): use it!lcs[i][j] = 1 + lcs[i + 1][j + 1](one letter, plus the best for the rest of both). - They differ: they can't both be matched here, so at least one of them is skipped. Try both options and keep the better one:
lcs[i][j] = max(lcs[i + 1][j], lcs[i][j + 1]). - Base case: if either string is used up (
iorjpast the end), the answer is0.
lcs[i][j] = 1 + lcs[i+1][j+1] if text1[i] === text2[j]
= max(lcs[i+1][j], lcs[i][j+1]) otherwiseThis is a 2-D DP: the state is two positions, one in each string, so the saved answers form a grid.
Step by step
text1 = "abcde" (rows), text2 = "ace" (columns). The extra row and column marked · are the "string used up" base cases (all 0). Fill from the bottom-right corner up, so every cell you need (below, right, and diagonally down-right) is already filled:
a c e ·
a 3 2 1 0
b 2 2 1 0
c 2 2 1 0
d 1 1 1 0
e 1 1 1 0
· 0 0 0 0A few cells, explained:
| Cell | Letters | Rule | Value |
|---|---|---|---|
row e, col e | match | 1 + diagonal (0) | 1 |
row c, col c | match | 1 + diagonal (row d, col e = 1) | 2 |
row b, col a | differ | max(below = 2, right = 2) | 2 |
row a, col a | match | 1 + diagonal (row b, col c = 2) | 3 |
Answer: lcs[0][0] = 3.
Saving memory: two rows
Each row only uses the row below it (and itself). So the code keeps just two arrays: below (the finished row i + 1) and row (the one being filled). That's O(n) memory instead of O(m · n).
The code
The reference solution is below, with comments on every important line.
How fast is it?
With m and n the two string lengths:
- Time: O(m · n). Each cell is computed once, in O(1).
- Memory: O(n) with two rows (O(m · n) with the full table).
Common mistakes
- Confusing subsequence with substring. The letters don't need to be next to each other.
- When the letters match, also trying the "skip" options. Not wrong, but unnecessary: using a match is never worse.
- When they differ, adding 1. Only a match adds 1.
- Off-by-one in the table size. It needs one extra row and column for the "used up" base cases.
Going deeper
- LCS is the core of
difftools (which lines stayed the same between two files) and DNA sequence comparison. - Edit Distance uses the same "match, or try each option" grid, with three options (insert, delete, replace) instead of two.
- Don't confuse it with Longest Increasing Subsequence (1-D DP), which looks at a single sequence.
Reference solution
/**
* @param {string} text1
* @param {string} text2
* @return {number}
*/
export default function longestCommonSubsequence(text1, text2) {
// lcs[i][j] = answer for text1 from i and text2 from j. We keep only two rows:
// `below` is the finished row i + 1. It starts as the "text1 used up" row: all 0.
let below = new Array(text2.length + 1).fill(0)
for (let i = text1.length - 1; i >= 0; i--) {
// row i, with an extra 0 at the end for "text2 used up"
const row = new Array(text2.length + 1).fill(0)
for (let j = text2.length - 1; j >= 0; j--) {
// Match: count it, plus the diagonal (rest of both strings).
// Differ: skip text1[i] (below[j]) or skip text2[j] (row[j + 1]), whichever is better.
row[j] = text1[i] === text2[j] ? 1 + below[j + 1] : Math.max(below[j], row[j + 1])
}
below = row // this row becomes the one below for the next i
}
return below[0] // lcs[0][0]: both strings from the start
}export default function longestCommonSubsequence(text1: string, text2: string): number {
// lcs[i][j] = answer for text1 from i and text2 from j. We keep only two rows:
// `below` is the finished row i + 1. It starts as the "text1 used up" row: all 0.
let below = new Array<number>(text2.length + 1).fill(0)
for (let i = text1.length - 1; i >= 0; i--) {
// row i, with an extra 0 at the end for "text2 used up"
const row = new Array<number>(text2.length + 1).fill(0)
for (let j = text2.length - 1; j >= 0; j--) {
// Match: count it, plus the diagonal (rest of both strings).
// Differ: skip text1[i] (below[j]) or skip text2[j] (row[j + 1]), whichever is better.
row[j] = text1[i] === text2[j] ? 1 + below[j + 1] : Math.max(below[j], row[j + 1])
}
below = row // this row becomes the one below for the next i
}
return below[0] // lcs[0][0]: both strings from the start
}def longest_common_subsequence(text1: str, text2: str) -> int:
# lcs[i][j] = answer for text1 from i and text2 from j. We keep only two rows:
# `below` is the finished row i + 1. It starts as the "text1 used up" row: all 0.
below = [0] * (len(text2) + 1)
for i in range(len(text1) - 1, -1, -1):
# row i, with an extra 0 at the end for "text2 used up"
row = [0] * (len(text2) + 1)
for j in range(len(text2) - 1, -1, -1):
if text1[i] == text2[j]:
# Match: count it, plus the diagonal (rest of both strings).
row[j] = 1 + below[j + 1]
else:
# Differ: skip text1[i] (below[j]) or skip text2[j] (row[j + 1]).
row[j] = max(below[j], row[j + 1])
below = row # this row becomes the one below for the next i
return below[0] # lcs[0][0]: both strings from the start