Longest common substring problem is one of famous problem in computer science.Experienced c/c++ programmer can face this type of problem. Given two or more strings ,find the longest common substring, for example the longest common substring of the strings “ABABC”, “BABCA” is string “ABC” of length 3 ( source: Wikipedia).

Let us Take another example: string_1 = “Hello” and string_2=”Fellow”, The longest common substring is “ello” of length 4.

Recursive approach:

  •  select first character from one string and select first character from second string.
  • if match continue with second character from both string ,increment the count.
  • if not matched select next character from one string and do match in second string and store the match count
  • select first character from string one and do match from next character in second string and store the match count.
  • return max of above two steps.

complexity: close to 2^n

As we can see the solution is correct, but look at the complexity. practically it is not possible to accept this code because of exponential complexity of above algorithm. in this solution same problem is solved repeatedly. Look at  below is an calling tree for lcs([B, A, C, B],[A, B, C, A, B]). we will find that we are solving some of sub-problems again and again.

lcstree

If we memorize the solution of sub-problem we can reduced the complexity. Let us modified the above code by memoization using 2d array. The memoization algorithm would compute the LCS in time O(m*n)  where m and n are length of two strings. if  the two strings are equal the time complexity would be O(n²).

Recursive approach with memoization ( dynamic programming)