Dynamic Programming – Longest Common Substring

Objective: Given two string sequences write an algorithm to find, find the length of longest substring present in both of them.

This problem has been asked in Amazon and Microsoft interviews. Approach to solve this problem will be slightly different than the approach in “Longest Common Subsequence

What is Longest Common Substring: A longest substring is a sequence that appears in the same order and necessarily contiguous in both the strings.


String A = "tutorialhorizon";

String B = "dynamictutorialProgramming";

Output: Length of Longest Common Substring: 8 ("tutorial").


Naive Approach:

Check all the substrings from first string with second string anxd keep track of the maximum.

Time Complexity: O(n2*m), O(n2) for the substring and O(m) for check all the substrings with second string.

Better Solution: Dynamic Programming

Earlier we have seen how to find “Longest Common Subsequence” in two given strings. Approach in this problem will be quite similar to that.

we will solve this problem in bottom-up manner. Create a matrix of size of m*n and store the solutions of substrings to use them later.

Base Cases: If any of the string is null then LCS will be 0.

Check if ith character in one string A is equal to jth character in string B

Case 1: both characters are same

LCS[i][j] = 1 + LCS[i-1][j-1] (add 1 to the result and remove the last character from both the strings and check the result for the smaller string.)

Case 2: both characters are not same.

LCS[i][j] = 0

At the end, traverse the matrix and find the maximum element in it, This will the length of Longest Common Substring.

See the code for better explanation.


public class LongestCommonSubString {
public static int find(char [] A, char [] B){
int [][]LCS = new int [A.length+1][B.length+1];
// if A is null then LCS of A, B =0
for(int i=0;i<=B.length;i++){
// if B is null then LCS of A, B =0
for(int i=0;i<=A.length;i++){
//fill the rest of the matrix
for(int i=1;i<=A.length;i++){
for(int j=1;j<=B.length;j++){
LCS[i][j] = LCS[i1][j1] +1;
LCS[i][j] = 0;
int result = 1;
for(int i=0;i<=A.length;i++){
for(int j=0;j<=B.length;j++){
result = LCS[i][j];
return result;
public static void main(String[] args) {
String A = "tutorialhorizon";
String B = "dynamictutorialProgramming";
System.out.println("LCS length : " + find(A.toCharArray(), B.toCharArray()));


LCS length : 8
Longest Common Substring Matrix
Longest Common Substring Matrix