Longest Common Subsequence
Medium
Topics
Given two strings text1 and text2, return the length of their longest common subsequence (characters in order, not necessarily contiguous). Return 0 if none.
Example 1
text1
text2
kept in both
The shaded characters read the same left to right in both strings —
ace — and they need not be adjacent, which is what separates a subsequence from a substring. The answer is how many there are, 3.Rows are the two strings; shaded cells are one longest sequence common to both.
Input: text1 = "abcde", text2 = "ace" Output: 3
Example 2
text1
text2
The two strings share no character in common order, so the answer is
0.Input: text1 = "abc", text2 = "def" Output: 0
Constraints
- 1 <= text1.length, text2.length <= 1000
- Inputs consist of lowercase English letters.
Editorial — intuition, approach, complexity and pitfalls
Intuition
Compare the two strings position by position. If the current characters match, the LCS grows by one from the diagonal; otherwise take the best of dropping one character from either string.
Approach
- dp[i][j] = LCS length of the first i chars of s and first j of t.
- If s[i-1] == t[j-1]: dp[i][j] = dp[i-1][j-1] + 1.
- Else dp[i][j] = max(dp[i-1][j], dp[i][j-1]).
Dry Run
s = "abcde" t = "ace"
dp[i][j] = LCS length of the first i characters of s and the first j of t.
"" a c e
"" 0 0 0 0
a 0 1 1 1
b 0 1 1 1
c 0 1 2 2
d 0 1 2 2
e 0 1 2 3
answer 3 -- the subsequence "ace"
Three rows do nothing at all. Row b and row d are identical to the rows above
them, because 'b' and 'd' appear nowhere in t, so the mismatch branch just carries
the best-so-far forward. The value only climbs on the diagonal steps at (a,a),
(c,c) and (e,e).
On a match the value comes from dp[i-1][j-1] + 1 -- the DIAGONAL -- because both
characters are consumed by the pairing. Adding 1 to max(dp[i-1][j], dp[i][j-1])
instead lets one character be spent twice: "ba" against "aac" then returns 2 when
the longest common subsequence is just "a".
On a mismatch the two candidates advance the strings independently, which is what
makes this a subsequence problem rather than a substring one. The matched
characters need not be adjacent in either string -- "ace" is spread across
"abcde" -- so neither index is forced to move in lockstep with the other.Complexity
- Time — O(m*n): fill the full table.
- Space — O(m*n): the DP grid (reducible to O(min(m,n))).
Common Pitfalls
- On a match the value is
dp[i-1][j-1] + 1-- the diagonal. Adding 1 tomax(dp[i-1][j], dp[i][j-1])instead lets the same character be consumed twice and overcounts:baagainstaacreturns 2 where the longest common subsequence is justa. - Subsequence, not substring. The characters need not be adjacent, which is exactly why the mismatch branch may advance either string independently.
Full Solution — all languages
class Solution:
def longestCommonSubsequence(self, s, t):
m,n=len(s),len(t)
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 s[i-1]==t[j-1] else max(dp[i-1][j],dp[i][j-1])
return dp[m][n]import java.util.*;
class Solution {
public int longestCommonSubsequence(String s, String t) {
int m=s.length(),n=t.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]=s.charAt(i-1)==t.charAt(j-1)?dp[i-1][j-1]+1:Math.max(dp[i-1][j],dp[i][j-1]);
return dp[m][n];
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: int longestCommonSubsequence(string s, string t) {
int m=s.size(),n=t.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]=s[i-1]==t[j-1]?dp[i-1][j-1]+1:max(dp[i-1][j],dp[i][j-1]);
return dp[m][n];
}
};/**
* @param {string} s
* @param {string} t
* @return {number}
*/ var longestCommonSubsequence = function(s, t) {
const m=s.length,n=t.length,dp=[];
for(let i=0;i<=m;i++)dp.push(new Array(n+1).fill(0));
for(let i=1;i<=m;i++)for(let j=1;j<=n;j++)dp[i][j]=s[i-1]===t[j-1]?dp[i-1][j-1]+1:Math.max(dp[i-1][j],dp[i][j-1]);
return dp[m][n];
};