Solution: Longest Common Substring
This review provides a detailed analysis of the different ways to solve the Longest Common Substring problem.
Solution #1: Brute force
Let’s start by discussing the brute force solution.
Explanation
This is a naive solution which finds all the substrings of the two given strings and then discovers the longest common substrings between the two.
-
If the strings have a matching character, we recursively check for the remaining length of each and keep a track of the current matching length (line 8).
-
If the characters don’t match, we start two new recursive calls by skipping those characters from each string (lines 10-11).
-
The length of the longest common substring will be the maximum number returned by the three recursive calls (line 13).
Time complexity
The time complexity of this code is exponential: .
Notice that the time complexity is so high that the function times out before it can process the longer inputs
s3ands4. Try uncommenting the call on line 28.
The space complexity is ...