Longest Common Substring in DSA C# - Time & Space Complexity
We want to understand how the time needed to find the longest common substring grows as the input strings get longer.
How does the work increase when the strings become bigger?
Analyze the time complexity of the following code snippet.
public int LongestCommonSubstring(string s1, string s2) {
int maxLen = 0;
int[,] dp = new int[s1.Length + 1, s2.Length + 1];
for (int i = 1; i <= s1.Length; i++) {
for (int j = 1; j <= s2.Length; j++) {
if (s1[i - 1] == s2[j - 1]) {
dp[i, j] = dp[i - 1, j - 1] + 1;
if (dp[i, j] > maxLen) maxLen = dp[i, j];
} else {
dp[i, j] = 0;
}
}
}
return maxLen;
}
This code finds the length of the longest substring that appears in both input strings by checking all pairs of characters and building up a table.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Nested loops comparing characters of both strings and updating the table.
- How many times: The outer loop runs for each character in the first string (n times), and the inner loop runs for each character in the second string (m times), so total n x m times.
As the strings get longer, the number of comparisons grows by multiplying their lengths.
| Input Size (n = length of s1, m = length of s2) | Approx. Operations |
|---|---|
| 10 and 10 | 100 |
| 100 and 100 | 10,000 |
| 1000 and 1000 | 1,000,000 |
Pattern observation: The work grows roughly by the product of the lengths, so doubling both strings makes the work about four times bigger.
Time Complexity: O(n x m)
This means the time needed grows proportionally to the product of the lengths of the two strings.
[X] Wrong: "Since we only check characters one by one, the time is O(n) or O(m)."
[OK] Correct: We actually compare every character of the first string with every character of the second string, so the total checks multiply, not just add.
Understanding this time complexity helps you explain how dynamic programming solves problems by breaking them into smaller parts and why nested loops matter for performance.
"What if we used a suffix tree or suffix array instead? How would the time complexity change?"
Practice
Solution
Step 1: Understand the problem definition
The Longest Common Substring problem looks for the longest sequence of characters that appear in both strings without any gaps.Step 2: Differentiate from similar problems
Unlike Longest Common Subsequence, substrings must be continuous in both strings.Final Answer:
The longest sequence of characters that appear consecutively in both strings -> Option AQuick Check:
Longest Common Substring = consecutive matching characters [OK]
- Confusing substring with subsequence
- Thinking characters can be non-continuous
- Counting total common characters instead of longest sequence
Solution
Step 1: Recall C# syntax for 2D arrays
In C#, a rectangular 2D array is declared as int[,] with sizes specified in new int[m + 1, n + 1].Step 2: Check each option
int[,] dp = new int[m + 1, n + 1]; uses correct syntax. Options A and D mix jagged and rectangular array syntax incorrectly. int[,] dp = new int[m][n]; uses wrong initialization syntax.Final Answer:
int[,] dp = new int[m + 1, n + 1]; -> Option CQuick Check:
Rectangular 2D array syntax = int[,] dp = new int[m + 1, n + 1]; [OK]
- Using jagged array syntax incorrectly
- Missing +1 for boundary conditions
- Mixing rectangular and jagged array syntax
string s1 = "abcde";
string s2 = "abfde";
int m = s1.Length;
int n = s2.Length;
int[,] dp = new int[m + 1, n + 1];
int maxLen = 0;
for (int i = 1; i <= m; i++) {
for (int j = 1; j <= n; j++) {
if (s1[i - 1] == s2[j - 1]) {
dp[i, j] = dp[i - 1, j - 1] + 1;
if (dp[i, j] > maxLen) maxLen = dp[i, j];
} else {
dp[i, j] = 0;
}
}
}
Console.WriteLine(maxLen);
Solution
Step 1: Trace matching characters between s1 and s2
Strings: s1 = "abcde", s2 = "abfde". Matching substrings are "ab" at start and "de" at end, both length 2.Step 2: Identify longest common substring length
Longest common substring length is 2, either "ab" or "de".Final Answer:
2 -> Option AQuick Check:
Longest common substring length = 2 [OK]
- Counting non-continuous matches
- Confusing substring length with subsequence length
- Off-by-one errors in indexing
string s1 = "hello";
string s2 = "yellow";
int m = s1.Length;
int n = s2.Length;
int[,] dp = new int[m, n];
int maxLen = 0;
for (int i = 1; i <= m; i++) {
for (int j = 1; j <= n; j++) {
if (s1[i - 1] == s2[j - 1]) {
dp[i, j] = dp[i - 1, j - 1] + 1;
if (dp[i, j] > maxLen) maxLen = dp[i, j];
} else {
dp[i, j] = 0;
}
}
}
Console.WriteLine(maxLen);
Solution
Step 1: Check dp array size and indexing
dp is declared as int[m, n], but loops access dp[i, j] with i and j up to m and n, causing index out of range.Step 2: Correct dp size for safe indexing
dp should be int[m+1, n+1] to allow indices from 0 to m and 0 to n safely.Final Answer:
The dp array size should be (m+1, n+1) to avoid index errors -> Option BQuick Check:
dp size = (m+1, n+1) for safe indexing [OK]
- Using dp size without +1 causes runtime errors
- Starting loops at 0 causes negative indexing
- Incorrect character indexing without -1
s1 = "xabxac" and s2 = "abcabxabcd", what is the length of their longest common substring?Solution
Step 1: Identify common substrings between s1 and s2
Check substrings like "abx", "bxa", "xab", "abxa". The longest common substring is "abxa" with length 4.Step 2: Confirm no longer substring exists
"abxac" is in s1 but not fully in s2 consecutively. So length 4 is maximum.Final Answer:
4 -> Option DQuick Check:
Longest common substring length = 4 [OK]
- Counting subsequence instead of substring
- Overestimating length by including non-continuous chars
- Ignoring overlapping substrings
Ready to prove it?
Pass the test and this pattern moves unknown
