Solving the Longest Common Substring Problem
Let's solve the Longest Common Substring problem using Dynamic Programming.
Statement
Given two strings s1
and s2
, you have to find the length of the Longest Common Substring (LCS) in both these strings.
Let’s say we have two strings, “helloworld” and “yelloword”, there are multiple common substrings, such as “llo”, “ello”, “ellowor”, “low”, and “d”. The longest common substring is “ellowor”, with length 7.
Constraints:
s1.length
,s2.length
s1
ands2
consist of only lowercase English characters.Spaces are not allowed.
Examples
No. | s1 | s2 | Length of LCS |
1 | helloworld | helloold | 5 |
2 | educativeexplore | educativeexpress | 12 |
3 | educativeisfun | algorithmsarefun | 3 |
Try it yourself
Implement your solution in the following playground.
import java.util.*;public class Main{public static int lcsLength (String input1, String input2) {// Write Your Code Herereturn 0;}}
Note: If you clicked the “Submit” button and the code timed out, this means that your solution needs to be optimized in terms of running time.
Hint: Use dynamic programming and see the magic.
Solution
We will first explore the naive recursive solution to this problem and then see how it can be improved using dynamic programming.
Naive approach
Let’s look at this problem on a smaller scale. We are comparing each character one by one with the other string. There can be three possibilities for the i
s1
and the j
s2
:
If both characters match, these could be part of a common substring, meaning we should count this character towards the length of the longest common substring.
i
character of s1
might match with(j+1)
character of s2
.j
...