Skip to main content

1143. Longest Common Subsequence, LeetCode

· 4 min read
Suraj Jha

Problem Statement

Given two strings text1 and text2, return the length of their longest common subsequence. If there is no common subsequence, return 0.

A subsequence of a string is a new string generated from the original string with some characters (can be none) deleted without changing the relative order of the remaining characters.

  • For example, "ace" is a subsequence of "abcde".

A common subsequence of two strings is a subsequence that is common to both strings.

Example 1:

Input: text1 = "abcde", text2 = "ace" 
Output: 3
Explanation: The longest common subsequence is "ace" and its length is 3.

Example 2:

Input: text1 = "abc", text2 = "abc"
Output: 3
Explanation: The longest common subsequence is "abc" and its length is 3.

Example 3:

Input: text1 = "abc", text2 = "def"
Output: 0
Explanation: There is no such common subsequence, so the result is 0.

Constraints:

  • 1 <= text1.length, text2.length <= 1000
  • text1 and text2 consist of only lowercase English characters.

Explanation

Let i1 and i2 be two pointer pointing at current index in string s1 and s2 respectively.

let dp(i1, i2, s1, s2) denotes the length of longest common subsequence in string s1[i1...n1] and s2[i2...n2].

If i1 == n1, implies s1[i1....n1] is empty.

Base Case: longest common subsequence of any string with empty string is 0. Therefore is any of i1 == n1 or i2 == n2 return 0.

Now, for any i1 and i2 there are 2 possibilities.

Solution

CPP: Recursive Brute Force Solution [Time Limit Exceeded]
class Solution {
private:
int dp(int i1, int i2, string &s1, string &s2) {
int n1 = s1.size();
int n2 = s2.size();

// Base Case
if(i1 == n1 || i2 == n2) return 0;

if(s1[i1] == s2[i2]) {
return max({
dp(i1+1, i2+1, s1, s2) + 1,
dp(i1, i2+1, s1, s2),
dp(i1+1, i2, s1, s2),
});
}
else {
return max({
dp(i1, i2+1, s1, s2),
dp(i1+1, i2, s1, s2),
});
}
}
public:
int longestCommonSubsequence(string text1, string text2) {
return dp(0, 0, text1, text2);
}
};
mnTime ComplexitySpace Complexity
size of string 1size of string 2O(max(m,n)*m*n)O(max(m,n))

References