> For the complete documentation index, see [llms.txt](https://coding-9.gitbook.io/untitled/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://coding-9.gitbook.io/untitled/dynamic-programming/dp-on-strings/longest-common-substring.md).

# Longest Common Substring

## Problem Statement

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

\
**Example 1:**

<pre><code><strong>Input: S1 = "ABCDGH", S2 = "ACDGHR", n = 6, m = 6
</strong><strong>Output: 4
</strong><strong>Explanation: The longest common substring
</strong>is "CDGH" which has length 4.
</code></pre>

**Example 2:**

<pre><code><strong>Input: S1 = "ABC", S2 "ACB", n = 3, m = 3
</strong><strong>Output: 1
</strong><strong>Explanation: The longest common substrings
</strong>are "A", "B", "C" all having length 1.
</code></pre>

\
**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

## Intuition

```
Approach:

We cannot memoize this, as this will boil down to LCS problem, Because if no
match we will have to return and cannot match earlier elements

So, We check for every character matching using bootom up and update the count


```

### Links

<https://practice.geeksforgeeks.org/problems/longest-common-substring1452/1>

### Video Links

### Approach 1:

```
```

{% code title="C++" lineNumbers="true" %}

```cpp
int longestCommonSubstr (string s1, string s2, int n, int m){
        int maxi=0;
        vector<vector<int>>dp(n+1,vector<int>(m+1,0));
        for(int i=1;i<=n;i++){
            for(int j=1;j<=m;j++){
                if(s1[i-1] == s2[j-1]){
                    dp[i][j]=dp[i-1][j-1]+1;
                    maxi=max(maxi,dp[i][j]);
                }
                
            }
        }
        return maxi;
    }
```

{% endcode %}

### Approach 2:

```
```

{% code title="C++" lineNumbers="true" %}

```cpp
```

{% endcode %}

### Approach 3:

```
```

{% code title="C++" lineNumbers="true" %}

```cpp
```

{% endcode %}

### Approach 4:

```
```

{% code title="C++" lineNumbers="true" %}

```cpp
```

{% endcode %}

### Similar Problems

###
