0% completed
Solution: Longest Common Substring
On This Page
Problem Statement
Basic Solution
Code
Top-down Dynamic Programming with Memoization
Code
Bottom-up Dynamic Programming
Challenge
Hint
Problem Statement
Given two strings 's1' and 's2', find the length of the longest substring which is common in both the strings.
Example 1:
Input: s1 = "abdca"
s2 = "cbda"
Output: 2
Explanation: The longest common substring is "bd".
Example 2:
Input: s1 = "passport"
s2 = "ppsspt"
Output: 3
Explanation: The longest common substring is "ssp".
Constraints:
- 1 <= s1.length, s2.length <= 1000`
s1ands2consist of only lowercase English characters.
Basic Solution
A basic brute-force solution could be to try all substrings of 's1' and 's2' to find the longest common one. We can start matching both the strings one character at a time, so we have two options at any step:
- If the strings have a matching character, we can recursively match for the remaining lengths and keep a track of the current matching length.
- If the strings don't match, we start two new recursive calls by skipping one character separately from each string and reset the matching length.
The length of the Longest Common Substring (LCS) will be the maximum number returned by the three recurse calls in the above two options.
Code
Here is the code:
Because of the three recursive calls, the time complexity of the above algorithm is exponential O(3^{m+n}), where 'm' and 'n' are the lengths of the two input strings. The space complexity is O(m+n), this space will be used to store the recursion stack.
Top-down Dynamic Programming with Memoization
We can use an array to store the already solved subproblems.
The three changing values to our recursive function are the two indexes (i1 and i2) and the 'count'. Therefore, we can store the results of all subproblems in a three-dimensional array. (Another alternative could be to use a hash-table whose key would be a string (i1 + "|" i2 + "|" + count)).
Code
Here is the code:
Bottom-up Dynamic Programming
Since we want to match all the substrings of the given two strings, we can use a two-dimensional array to store our results. The lengths of the two strings will define the size of the two dimensions of the array. So for every index 'i' in string 's1' and 'j' in string 's2', we have two options:
- If the character at
s1[i]matchess2[j], the length of the common substring would be one plus the length of the common substring tilli-1andj-1indexes in the two strings. - If the character at the
s1[i]does not matchs2[j], we don't have any common substring.
So our recursive formula would be:
if s1[i] == s2[j] dp[i][j] = 1 + dp[i-1][j-1] else dp[i][j] = 0
Let's draw this visually for "abcda" and "cbda". Starting with a substring of zero lengths, if any one of the string has zero length, then the common substring will be of zero length:
From the above visualization, we can clearly see that the longest common substring is of length '2'-- as shown by dp[3][3].
Here is the code for our bottom-up dynamic programming approach:
The time and space complexity of the above algorithm is O(m*n), where 'm' and 'n' are the lengths of the two input strings.
Challenge
Can we further improve our bottom-up DP solution? Can you find an algorithm that has O(n) space complexity?
Hint
We only need one previous row to find the optimal solution!
Gary
· 4 years ago
Why does the bottom-up table seem to have incorrect values for some positions, like dp[2][3], which means the longest common substring between "cb" and "abd", which should be 1 instead of 0 since "b" is the one common substring?
Lucifer
· 4 years ago
what is the time and space complexity of the top-down solution?
Gaurav Sisodiya
· 4 years ago
@designgurus - It would be great if you could add some explaination for the space optimal solution and make it more elaborative.
Peng Xu
· 3 years ago
For below test case when s1="passport" and s2 = "ppsspt"
I got result 1 for the longest common substring. Seems the solution might not be correct. could you help to check?
class Solution: def findLCSLength(self, s1, s2): # TODO: Write your code here # index 1 and 2 def helper(i1, i2, count): if i1 == len(s1) or i2 == len(s2): return count if s1[i1] == s2[i2]: return helper(i1+1, i2 + 1, count + 1) else: c1 = helper(i1, i2 +1, 0) c2 = helper(i1+1, i2, 0) c3 = helper(i1 + 1, i2 + 1, 0) return max(c1, c2, c3) return helper(0,0, 0)
On This Page
Problem Statement
Basic Solution
Code
Top-down Dynamic Programming with Memoization
Code
Bottom-up Dynamic Programming
Challenge
Hint