Longest Common Subsequence
Longest Common Subsequence is a medium dynamic programming problem solved with the strings pattern.
The best approach, optimal (two rows), runs in O(m · n) time and O(n) space.
Below are 3 approaches in Java, Python, C++ and JavaScript, from recursion up.
Problem
Return the length of the longest common subsequence of two strings: the longest sequence of characters that appears in both, in order, but not necessarily contiguously.
Examples
Example 1
- Input
text1 = "abcde", text2 = "ace"- Output
3
Example 2
- Input
text1 = "abc", text2 = "def"- Output
0
Constraints
1 <= length <= 1000; lowercase letters.- A subsequence keeps order but may skip characters.
Solve it here
Write your solution in Java, Python, C++ or JavaScript and run it against the examples, right in the page. Submit runs the hidden tests too and, with a free account, records the solve in your revision log.
Your own testcases: Run checks these, and the expected output comes from our reference solution.
My submissions
Nothing yet. Every Run and Submit you make while signed in shows up here.
| When | Result | Tests | Runtime | Your time | Type |
|---|
Run checks the testcases above (2 examples, or your own). Submit also runs 10 hidden tests and saves the solve to your log. Signed in, every Run and Submit is saved under My submissions; your draft stays in this browser.
Animated walkthrough
A narrated, step-by-step animation that builds the solution from the idea up. Press play, or step through it at your own pace.
Concepts first, then the problem and every approach, step by step.
Space to play or pause · ← → to jump a step · click or drag the bar to seek
Solutions
Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the code in Java, Python, C++ and JavaScript.
| Approach | Time | Space |
|---|---|---|
| Recursion | O(2^(m + n)) | O(m + n) |
| Tabulation (2D) | O(m · n) | O(m · n) |
| Optimal (two rows) | O(m · n) | O(n) |
1Recursion
O(2^(m + n))O(m + n)Compare the last characters; match → take both; otherwise try dropping either one.
- f(0, ) = f(, 0) = 0.
class Solution {
public int longestCommonSubsequence(String a, String b) {
return f(a, b, a.length(), b.length());
}
private int f(String a, String b, int i, int j) {
if (i == 0 || j == 0) return 0;
if (a.charAt(i - 1) == b.charAt(j - 1)) return 1 + f(a, b, i - 1, j - 1);
return Math.max(f(a, b, i - 1, j), f(a, b, i, j - 1));
}
}class Solution:
def longestCommonSubsequence(self, a: str, b: str) -> int:
return self.f(a, b, len(a), len(b))
def f(self, a: str, b: str, i: int, j: int) -> int:
if i == 0 or j == 0:
return 0
if a[i - 1] == b[j - 1]:
return 1 + self.f(a, b, i - 1, j - 1)
return max(self.f(a, b, i - 1, j), self.f(a, b, i, j - 1))class Solution {
public:
int longestCommonSubsequence(string a, string b) {
return f(a, b, a.size(), b.size());
}
private:
int f(const string& a, const string& b, int i, int j) {
if (i == 0 || j == 0) return 0;
if (a[i - 1] == b[j - 1]) return 1 + f(a, b, i - 1, j - 1);
return max(f(a, b, i - 1, j), f(a, b, i, j - 1));
}
};function longestCommonSubsequence(a, b) {
return f(a, b, a.length, b.length);
}
function f(a, b, i, j) {
if (i === 0 || j === 0) return 0;
if (a[i - 1] === b[j - 1]) return 1 + f(a, b, i - 1, j - 1);
return Math.max(f(a, b, i - 1, j), f(a, b, i, j - 1));
}2Tabulation (2D)
O(m · n)O(m · n)dp[i][j] = LCS of the first i characters of a and the first j of b.
- Match: dp[i - 1][j - 1] + 1. Else max(dp[i - 1][j], dp[i][j - 1]).
class Solution {
public int longestCommonSubsequence(String a, String b) {
int m = a.length(), n = b.length();
int[][] dp = new int[m + 1][n + 1];
for (int i = 1; i <= m; i++)
for (int j = 1; j <= n; j++)
dp[i][j] = a.charAt(i - 1) == b.charAt(j - 1)
? dp[i - 1][j - 1] + 1
: Math.max(dp[i - 1][j], dp[i][j - 1]);
return dp[m][n];
}
}class Solution:
def longestCommonSubsequence(self, a: str, b: str) -> int:
m, n = len(a), len(b)
dp = [[0] * (n + 1) for _ in range(m + 1)]
for i in range(1, m + 1):
for j in range(1, n + 1):
dp[i][j] = (dp[i - 1][j - 1] + 1 if a[i - 1] == b[j - 1]
else max(dp[i - 1][j], dp[i][j - 1]))
return dp[m][n]class Solution {
public:
int longestCommonSubsequence(string a, string b) {
int m = a.size(), n = b.size();
vector<vector<int>> dp(m + 1, vector<int>(n + 1, 0));
for (int i = 1; i <= m; i++)
for (int j = 1; j <= n; j++)
dp[i][j] = a[i - 1] == b[j - 1]
? dp[i - 1][j - 1] + 1
: max(dp[i - 1][j], dp[i][j - 1]);
return dp[m][n];
}
};function longestCommonSubsequence(a, b) {
const m = a.length, n = b.length;
const dp = Array.from({ length: m + 1 }, () => new Array(n + 1).fill(0));
for (let i = 1; i <= m; i++)
for (let j = 1; j <= n; j++)
dp[i][j] = a[i - 1] === b[j - 1]
? dp[i - 1][j - 1] + 1
: Math.max(dp[i - 1][j], dp[i][j - 1]);
return dp[m][n];
}3Optimal (two rows)
O(m · n)O(n)Keep only the previous and current rows.
- Swap rows after each i.
class Solution {
public int longestCommonSubsequence(String a, String b) {
int m = a.length(), n = b.length();
int[] prev = new int[n + 1], cur = new int[n + 1];
for (int i = 1; i <= m; i++) {
for (int j = 1; j <= n; j++)
cur[j] = a.charAt(i - 1) == b.charAt(j - 1) ? prev[j - 1] + 1 : Math.max(prev[j], cur[j - 1]);
int[] t = prev; prev = cur; cur = t;
}
return prev[n];
}
}class Solution:
def longestCommonSubsequence(self, a: str, b: str) -> int:
m, n = len(a), len(b)
prev, cur = [0] * (n + 1), [0] * (n + 1)
for i in range(1, m + 1):
for j in range(1, n + 1):
cur[j] = prev[j - 1] + 1 if a[i - 1] == b[j - 1] else max(prev[j], cur[j - 1])
prev, cur = cur, prev
return prev[n]class Solution {
public:
int longestCommonSubsequence(string a, string b) {
int m = a.size(), n = b.size();
vector<int> prev(n + 1, 0), cur(n + 1, 0);
for (int i = 1; i <= m; i++) {
for (int j = 1; j <= n; j++)
cur[j] = a[i - 1] == b[j - 1] ? prev[j - 1] + 1 : max(prev[j], cur[j - 1]);
swap(prev, cur);
}
return prev[n];
}
};function longestCommonSubsequence(a, b) {
const m = a.length, n = b.length;
let prev = new Array(n + 1).fill(0), cur = new Array(n + 1).fill(0);
for (let i = 1; i <= m; i++) {
for (let j = 1; j <= n; j++)
cur[j] = a[i - 1] === b[j - 1] ? prev[j - 1] + 1 : Math.max(prev[j], cur[j - 1]);
[prev, cur] = [cur, prev];
}
return prev[n];
}Edge cases to test
- No common letters
- One string inside the other
Hints
Hint 1
If the last characters match, they are both in the LCS: 1 + dp[i - 1][j - 1]. Otherwise drop one of them: max(dp[i - 1][j], dp[i][j - 1]).
FAQ
What is the best time complexity for Longest Common Subsequence?
Optimal (two rows) runs in O(m · n) time and O(n) extra space.
Which pattern does Longest Common Subsequence use?
It is a dynamic programming problem that uses the strings pattern. Other problems with the same pattern: Edit Distance, Longest Palindromic Subsequence, Minimum Insertion Steps to Make a String Palindrome.
Is there a brute force solution for Longest Common Subsequence?
Yes. Recursion takes O(2^(m + n)) time and O(m + n) space. Compare the last characters; match → take both; otherwise try dropping either one.
Which edge cases should I test for Longest Common Subsequence?
No common letters; One string inside the other.