Longest Common Subsequence
Medium · Dynamic programming
Jump to codeFind the length of the longest sequence obtainable from each of two strings by deleting characters without reordering those kept.
Examples
Example 1
text1 = "abcde" text2 = "ace"
Output: 3
Example 2
text1 = "abc" text2 = "abc"
Output: 3
Constraints
- 1 <= text1.length, text2.length <= 1000
- text1 and text2 consist of only lowercase English characters.
Need a hint?
Compare the final characters of two prefixes.
Asked in real interviews
Candidates reported versions of Longest Common Subsequence from these company interviews. Some company questions are locked and open with Premium or XP.
- Compute longest common subsequence lengthRoku
- Find longest common subsequence lengthTikTok
- Find length of longest common subsequenceTikTok
Solution approach
For matching characters, extend the diagonal prefix result by one. Otherwise take the maximum after dropping the last character from either prefix. Initialize the empty row and column to zero. Two rows suffice if you preserve the previous row while filling the current one.
Complexity
O(mn) time and O(n) space with two rows.
Python reference solution
def longestCommonSubsequence(text1, text2):
previous = [0] * (len(text2) + 1)
for a in text1:
current = [0] * (len(text2) + 1)
for j, b in enumerate(text2, 1):
current[j] = previous[j - 1] + 1 if a == b else max(previous[j], current[j - 1])
previous = current
return previous[-1]
JavaScript solution
function longestCommonSubsequence(text1, text2) {
let previous = Array(text2.length + 1).fill(0);
for (const a of text1) {
const current = Array(text2.length + 1).fill(0);
for (let j = 1; j <= text2.length; j++) {
current[j] = a === text2[j - 1] ? previous[j - 1] + 1 : Math.max(previous[j], current[j - 1]);
}
previous = current;
}
return previous[text2.length];
}
Java solution
import java.util.*;
class Solution {
public int longestCommonSubsequence(String text1, String text2) {
int[] previous = new int[text2.length() + 1];
for (int i = 0; i < text1.length(); i++) {
char a = text1.charAt(i);
int[] current = new int[text2.length() + 1];
for (int j = 1; j <= text2.length(); j++) {
current[j] = a == text2.charAt(j - 1) ? previous[j - 1] + 1 : Math.max(previous[j], current[j - 1]);
}
previous = current;
}
return previous[text2.length()];
}
}
C++ solution
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int longestCommonSubsequence(string text1, string text2) {
vector<int> previous(text2.size() + 1);
for (char a : text1) {
vector<int> current(text2.size() + 1);
for (size_t j = 1; j <= text2.size(); j++) {
current[j] = a == text2[j - 1] ? previous[j - 1] + 1 : max(previous[j], current[j - 1]);
}
previous = move(current);
}
return previous.back();
}
};
Trace a boundary case, then implement the approach in the editor. Submit checks your solution against all 8 test cases.
Keep your reasoning, pseudocode, and edge cases here.
Notes stay in this browser when storage is available.
Accepted submissions mark this problem complete. Progress stays in this browser.
[ "abcde", "ace" ]
3
[ "abc", "abc" ]
3
[ "abc", "def" ]
0
[ "abc", "ac" ]
2
[ "", "abc" ]
0
Drafts are saved per language in this browser when storage is available.