Longest Common Substring | Practice | GeeksforGeeks

Given two strings. The task is to find the length of the longest common substring.

Example 1:
Input: S1 = "ABCDGH", S2 = "ACDGHR"
Output: 4
Explanation: The longest common substring
is "CDGH" which has length 4.

Example 2:
Input: S1 = "ABC", S2 "ACB"
Output: 1
Explanation: The longest common substrings
are "A", "B", "C" all having length 1.


Your Task:
You don't need to read input or print anything. Your task is to complete the function longestCommonSubstr() which takes the string S1, string S2 and their length n and m as inputs and returns the length of the longest common substring in S1 and S2.

Expected Time Complexity: O(n*m).
Expected Auxiliary Space: O(n*m).

Constraints:
1<=n, m<=1000
0
aamitprasad6189 hours ago
CPP
 
int dp[n+1][m+1], ans = 0;
        
        memset(dp, 0, sizeof(dp));
        
        for(int i=1; i<=n; i++){
            for(int j=1; j<=m ;j++){
                if(S1[i-1] == S2[j-1]){
                    dp[i][j] = 1+dp[i-1][j-1];
                    ans = max(ans, dp[i][j]);
                }
                else{
                    dp[i][j] = 0;
                }
            }
        }
        return ans;
+1
kesharinandan152 days ago
 int longestCommonSubstr (string s1, string s2, int n, int m)
   {
       int ans=0;
       vector<vector<int>> dp(n+1, vector<int> (m+1, 0));
   		for(int i = 1; i < n+1; i++){
        	for(int j = 1; j < m+1; j++){
            	if(s1[i-1] == s2[j-1] ){
                	dp[i][j] = dp[i-1][j-1] + 1;
                	ans = max(ans , dp[i][j]);
            }
        }
    }
    	return ans;
   }
};
0
yashmukaty12 days ago
don't get confused it with Longest common subsequence. They are asking for SUBSTRING not SUBSEQUENCE. 
0
abhishek0908024 days ago
int longestCommonSubstr (string S1, string S2, int n, int m)
    {
        vector<int>prev(m+1,0); 
        vector<int>cur(m+1,0);
        int ans=0; 
        for(int i=1;i<=n;i++)
        {
            for(int j=1;j<=m;j++)
            {
                if(S1[i-1]==S2[j-1])
              {   cur[j]=1+prev[j-1];
                  ans=max(ans,cur[j]);}
                else cur[j]=0;
            }
            prev=cur;
        }
        return ans;
    }
+2
shashikantkumar191it2495 days ago
memoization cpp
 
int solve(string &s1,string &s2,int m,int n,vector<vector<int>>&dp,int &ans)   {       if(m<0 or n<0)       {           return 0;       }       if(dp[m][n]!=-1)       {           return dp[m][n];       }       int take=0;       int t=0;       int t1=0;       if(s1[m]==s2[n])       {            take=1+solve(s1,s2,m-1,n-1,dp,ans);           // return dp[m][n]= 1+solve(s1,s2,m-1,n-1,dp);           // ans=max(ans,take);           // dp[m][n]=take;           // return take;       }       // else       // {           t=solve(s1,s2,m-1,n,dp,ans);           t1=solve(s1,s2,m,n-1,dp,ans);           ans=max(ans,take);           return dp[m][n]=take ;       // }   }   int longestCommonSubstr (string s1, string s2, int n, int m)   {       // your code here       int ans=INT_MIN;       vector<vector<int>>dp(n+1,vector<int>(m+1,-1));       int res= solve(s1,s2,n-1,m-1,dp,ans);       return ans;   }
0
aditya_njr5 days ago
// Space Optimised DP
 
class Solution{
    public:
    int longestCommonSubstr(string S1, string S2, int n, int m){
        int ans = 0;
        vector<int> prev(m + 1, 0), curr(m + 1, 0);
        for(int i=0; i<=n; i++){
            for(int j=0; j<=m; j++){
                if(i==0 || j == 0){
                    curr[j] = 0;
                }
                else if(S1[i-1] == S2[j-1]){
                    curr[j] = 1 + prev[j-1];
                    ans = max(ans, curr[j]);
                }
                else{
                    curr[j] = 0;
                }
            }
            prev = curr;
        }
        return ans;
    }
};
+1
2019sushilkumarkori5 days ago
int longestCommonSubstr (string S1, string S2, int n, int m)
    {
        int t[n+1][m+1],ans = 0;
        for(int i=0;i<=n;i++){
            for(int j=0;j<=m;j++){
                if(i==0 || j == 0){
                    t[i][j] = 0;
                }
            }
        }
        for(int i=1;i<=n;i++){
            for(int j=1;j<=m;j++){
                if(S1[i-1] == S2[j-1]){
                    t[i][j] = 1+t[i-1][j-1];
                    ans = max(ans,t[i][j]);
                }
                else{
                    t[i][j] = 0;
                }
            }
        }
        return ans;
    }
-1
shubratparth5 days ago
int dp[1001][1001];
    int longestCommonSubstr (string S1, string S2, int n, int m)
    {
        //Base case initialzation
        for(int i = 0 ; i < n ; i++){
            for(int j = 0 ; j < m ; j++){
                if(i == 0 || j == 0){
                    dp[i][j] = 0;
                }
            }
        }
        
        //In LCS we would have taken max of these i - 1 & j - 1 stuffs, but here
        //if the previous one do not match simply fill the block with 0
        //ie, ask for prev guy if they did match add one to it and fill the new block
        for(int i = 1 ; i <= n ; i++){
            for(int j = 1 ; j <= m ; j++){
                if(S1[i - 1] == S2[j - 1]){
                    dp[i][j] = 1 + dp[i - 1][j - 1];
                }else{
                    dp[i][j] = 0;
                }
            }
        }
        
        int max=INT_MIN;
          for(int i=0;i<=n;i++)
          {
              for(int j=0;j<=m;j++)
              {
                 if(dp[i][j]>max)
                 {
                     max=dp[i][j];
                 }
              }
          }
          return max;
    }
0
chessnoobdj6 days ago
C++ dp
int longestCommonSubstr (string S1, string S2, int n, int m){
        int dp[n+1][m+1], ans = 0;
        memset(dp, 0, sizeof(dp));
        for(int i=1; i<=n; i++){
            for(int j=1; j<=m ;j++){
                if(S1[i-1] == S2[j-1])
                    dp[i][j] = 1+dp[i-1][j-1];
                else
                    dp[i][j] = 0;
                ans = max(ans, dp[i][j]);
            }
        }
        return ans;
    }
0
chessnoobdj6 days ago
C++ greedy
int longestCommonSubstr (string S1, string S2, int n, int m){
        if(n < m){
            swap(S1, S2);
            swap(n, m);
        }
        int ans = 0;
        S1 += S1;
        for(int i=0; i<n; i++){
            int c = 0;
            for(int j=0; j<m; j++){
                if(S1[i+j] == S2[j])
                    c += 1;
                else{
                    ans = max(ans, c);
                    c = 0;
                }
            }
            ans = max(ans, c);
        }
        return ans;
    }
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested 
                                    against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code.
                                    On submission, your code is tested against multiple test cases consisting of all
                                        possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as
                                        the final solution code.
You can view the solutions submitted by other users from the submission tab.
Make sure you are not using ad-blockers.
Disable browser extensions.
We recommend using latest version of your browser for best experience.
Avoid using static/global variables in coding problems as your code is tested 
                                against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases in coding problems does not guarantee the 
                                correctness of code. On submission, your code is tested against multiple test cases
                                    consisting of all possible corner cases and stress constraints.