πΉ Definition
π Longest substring that is:
- Present in both strings
- Continuous (no skipping allowed) β
πΉ Difference from LCS
| Feature | Subsequence | Substring |
|---|---|---|
| Continuous | β | β |
| DP reset | β | β (important) |
π₯ Core Idea
If characters match:
dp[i][j] = 1 + dp[i-1][j-1]
If NOT match:
dp[i][j] = 0 // π₯ RESET (this is key difference)
πΉ Code (Correct & Clean C++)
int longestCommonSubstring(string s1, string s2) {
int n = s1.size(), m = s2.size();
vector<vector<int>> dp(n+1, vector<int>(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]){
dp[i][j] = 1 + dp[i-1][j-1];
ans = max(ans, dp[i][j]);
}
else{
dp[i][j] = 0; // π₯ important
}
}
}
return ans;
}
πΉ Optimized Space (O(m)) π
int longestCommonSubstring(string s1, string s2) {
int n = s1.size(), m = s2.size();
vector<int> prev(m+1, 0), curr(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]){
curr[j] = 1 + prev[j-1];
ans = max(ans, curr[j]);
}
else{
curr[j] = 0; // reset
}
}
prev = curr;
}
return ans;
}
π₯ Print Longest Common Substring
π Trick:
- Track ending index
- Extract substring
πΉ Code (Print substring)
string printLCSubstring(string s1, string s2) {
int n = s1.size(), m = s2.size();
vector<vector<int>> dp(n+1, vector<int>(m+1, 0));
int maxLen = 0;
int endIndex = 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] = 1 + dp[i-1][j-1];
if(dp[i][j] > maxLen){
maxLen = dp[i][j];
endIndex = i; // track end
}
}
}
}
return s1.substr(endIndex - maxLen, maxLen);
}
πΉ Example
s1 = "abcde"
s2 = "abfce"
π Output:
"ab"
π§ Key Intuition
Match β extend substring
Not match β break (reset to 0)
β οΈ Common Mistake
β Writing:
dp[i][j] = max(...)
π That is LCS (wrong problem)
π₯ Interview Tip
If interviewer says:
βLongest common substringβ
π Immediately think:
βReset DP to 0 when mismatchβ
π Summary
- Substring = continuous β reset DP
- Use diagonal only
- Track max length
If you want next level:
β
Difference table (LCS vs substring vs subsequence problems)
β
Hard problems based on this
β
Visual DP table like your image
Just tell me π
Top comments (0)