Longest Common Substring in DSA Rust - 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.
fn longest_common_substring(s1: &str, s2: &str) -> usize {
let bytes1 = s1.as_bytes();
let bytes2 = s2.as_bytes();
let mut max_len = 0;
let mut dp = vec![vec![0; bytes2.len() + 1]; bytes1.len() + 1];
for i in 1..=bytes1.len() {
for j in 1..=bytes2.len() {
if bytes1[i - 1] == bytes2[j - 1] {
dp[i][j] = dp[i - 1][j - 1] + 1;
if dp[i][j] > max_len {
max_len = dp[i][j];
}
}
}
}
max_len
}
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 of matching lengths.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Nested loops comparing characters of both strings.
- How many times: Outer loop runs once for each character in the first string (n times), inner loop runs once for each character in the second string (m times).
For each character in the first string, the code compares it with every character in the second string, so the work grows with the product of their lengths.
| Input Size (n = length of s1, m = length of s2) | Approx. Operations |
|---|---|
| 10 and 10 | 100 comparisons |
| 100 and 100 | 10,000 comparisons |
| 1000 and 1000 | 1,000,000 comparisons |
Pattern observation: The number of operations grows roughly by the product of the input sizes.
Time Complexity: O(n * m)
This means the time needed grows proportionally to the product of the lengths of the two strings.
[X] Wrong: "The algorithm only looks at each string once, so it must be O(n + m)."
[OK] Correct: Because it compares every character of one string with every character of the other, the work multiplies, not adds.
Understanding this time complexity helps you explain how dynamic programming solves problems by breaking them into smaller parts and why nested loops increase work quickly.
"What if we only compared substrings starting at the same index in both strings? How would the time complexity change?"
Practice
Solution
Step 1: Understand the problem definition
The Longest Common Substring problem looks for the longest continuous sequence of characters that appears in both strings without interruption.Step 2: Differentiate from similar problems
Unlike Longest Common Subsequence, which allows gaps, Longest Common Substring requires characters to be consecutive.Final Answer:
The longest sequence of characters that appears in both strings consecutively -> Option AQuick Check:
Longest Common Substring = consecutive matching characters [OK]
- Confusing substring with subsequence
- Thinking characters can be non-consecutive
- Counting total common characters instead of longest sequence
Solution
Step 1: Understand dimensions for DP table
For strings of length m and n, dp table size should be (m+1) x (n+1) to include empty prefixes.Step 2: Check Rust vector initialization syntax
vec![vec![0; n + 1]; m + 1] creates m+1 rows each with n+1 zeros, matching DP table size.Final Answer:
let mut dp = vec![vec![0; n + 1]; m + 1]; -> Option AQuick Check:
DP table size = (m+1) x (n+1) [OK]
- Swapping m and n in vector sizes
- Forgetting +1 for empty string row/column
- Using immutable vector when mutability is needed
s1 = "abcde" and s2 = "abfde"?
let s1 = "abcde";
let s2 = "abfde";
let m = s1.len();
let n = s2.len();
let mut dp = vec![vec![0; n + 1]; m + 1];
let mut max_len = 0;
for i in 1..=m {
for j in 1..=n {
if s1.as_bytes()[i - 1] == s2.as_bytes()[j - 1] {
dp[i][j] = dp[i - 1][j - 1] + 1;
if dp[i][j] > max_len {
max_len = dp[i][j];
}
}
}
}
println!("{}", max_len);Solution
Step 1: Compare characters and fill DP table
Matching characters are 'a' and 'b' at start, then 'd' and 'e' at the end. The longest continuous match is "ab" with length 2.Step 2: Track max_len during iteration
max_len updates to 1 for 'a', then 2 for 'b', resets for mismatch, then 1 for 'd' and 1 for 'e'. So max_len = 2.Final Answer:
2 -> Option CQuick Check:
Longest common substring length = 2 [OK]
- Counting non-consecutive matches
- Confusing substring length with subsequence length
- Ignoring reset of dp on mismatch
let s1 = "hello";
let s2 = "yellow";
let m = s1.len();
let n = s2.len();
let mut dp = vec![vec![0; n]; m];
let mut max_len = 0;
for i in 1..=m {
for j in 1..=n {
if s1.as_bytes()[i - 1] == s2.as_bytes()[j - 1] {
dp[i][j] = dp[i - 1][j - 1] + 1;
if dp[i][j] > max_len {
max_len = dp[i][j];
}
}
}
}
println!("{}", max_len);Solution
Step 1: Check DP vector initialization
DP vector is initialized with size m x n, but loops access dp[i][j] with i and j starting at 1, causing out-of-bounds error.Step 2: Correct DP vector size
DP vector should be sized (m+1) x (n+1) to safely access dp[i][j] for i and j in 1..=m and 1..=n.Final Answer:
DP vector size is incorrect; should be (m+1) x (n+1) -> Option BQuick Check:
DP size must match loop indices [OK]
- Using wrong DP vector size causing panic
- Starting loops at 0 but indexing with i-1
- Confusing bytes and chars for comparison
s1 = "ababc" and s2 = "babca", write a Rust function to find the longest common substring and return it. What is the correct longest common substring?Solution
Step 1: Use DP to find longest common substring length and end index
By comparing characters and updating dp, the longest common substring length is 3, ending at index 4 in s1.Step 2: Extract substring from s1 using end index and length
Substring of length 3 ending at index 4 in s1 is "abc".Final Answer:
"abc" -> Option DQuick Check:
Longest common substring = "abc" length 3 [OK]
- Choosing substring from wrong string
- Confusing substring with subsequence
- Not updating end index when max length changes
Ready to prove it?
Pass the test and this pattern moves unknown
