📖 Scenario: Imagine you are building a simple text comparison tool. You want to find the longest part that two texts share exactly. This helps in finding common phrases or repeated patterns.
🎯 Goal: Build a program that finds the longest common substring between two given strings.
📋 What You'll Learn
Create two string variables with exact values
Create an integer variable to store the maximum length found
Use nested loops to compare substrings of both strings
Print the longest common substring found
💡 Why This Matters
🌍 Real World
Finding common substrings is useful in text comparison tools, plagiarism detection, and DNA sequence analysis.
💼 Career
Understanding string algorithms and nested loops is important for software developers working with text processing, search engines, and bioinformatics.
Progress0 / 4 steps
1
Create the input strings
Create two string variables called str1 and str2 with these exact values: "blueberry" and "blackberry"
DSA C++
Hint
Use std::string to create the two strings exactly as given.
2
Create a variable to store the maximum length
Create an integer variable called maxLength and set it to 0 to keep track of the longest common substring length
DSA C++
Hint
Use int maxLength = 0; to start counting the longest substring length.
3
Find the longest common substring length
Use nested for loops with variables i and j to iterate over str1 and str2. Inside, use a while loop with variable length to count matching characters. Update maxLength if length is greater.
DSA C++
Hint
Use nested loops to check every starting position in both strings. Use a while loop to count matching characters. Update maxLength when a longer match is found.
4
Print the longest common substring
Use nested for loops with variables i and j to find the first substring in str1 and str2 with length equal to maxLength. Print this substring using std::cout.
DSA C++
Hint
After finding maxLength, search again for the substring with this length and print it using std::cout. Use str1.substr(i, maxLength) to get the substring.
Practice
(1/5)
1. What does the Longest Common Substring problem find between two strings s1 and s2?
easy
A. The longest sequence of characters that appear contiguously in both strings
B. The longest sequence of characters that appear in both strings but not necessarily contiguously
C. The total number of common characters between the two strings
D. The longest string formed by concatenating both strings
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 any breaks.
Step 2: Differentiate from similar problems
Unlike Longest Common Subsequence, which allows gaps, Longest Common Substring requires characters to be contiguous in both strings.
Final Answer:
The longest sequence of characters that appear contiguously in both strings -> Option A
Quick Check:
Longest Common Substring = contiguous matching characters [OK]
Hint: Look for continuous matching characters in both strings [OK]
Common Mistakes:
Confusing substring with subsequence
Thinking characters can be non-contiguous
Counting total common characters instead of longest continuous
2. Which of the following C++ code snippets correctly initializes a 2D vector dp of size m+1 by n+1 with all zeros for Longest Common Substring?
easy
A. std::vector dp(m+1, std::vector<int>(n+1, 0));
B. std::vector<int> dp(m+1, std::vector<int>(n+1, 0));
To create a 2D vector with m+1 rows and n+1 columns filled with zeros, use nested vector initialization.
Step 2: Check each option
std::vector dp(m+1, std::vector<int>(n+1, 0)); correctly creates a vector of vectors with m+1 rows, each row a vector of n+1 zeros. Others have syntax errors or wrong types.
Final Answer:
std::vector dp(m+1, std::vector<int>(n+1, 0)); -> Option A
Hint: Use nested vector constructor for 2D zero initialization [OK]
Common Mistakes:
Using wrong vector types in initialization
Missing inner vector initialization
Trying to pass three arguments to vector constructor
3. What is the output of the following C++ code snippet?
std::string s1 = "abcdxyz";
std::string s2 = "xyzabcd";
int m = s1.size(), n = s2.size();
std::vector dp(m+1, std::vector<int>(n+1, 0));
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;
maxLen = std::max(maxLen, dp[i][j]);
}
}
}
std::cout << maxLen << std::endl;
medium
A. 3
B. 4
C. 1
D. 0
Solution
Step 1: Trace matching substrings
The longest common substring is "abcd" (length 4), which appears contiguously at the start of s1 and end of s2. "xyz" is length 3.
Step 2: Check dp updates and maxLen
dp updates length for matching characters. The longest continuous match found is length 4 for "abcd".
Final Answer:
4 -> Option B
Quick Check:
Longest common substring length = 4 [OK]
Hint: Check continuous matching segments, not total matches [OK]
Common Mistakes:
Confusing substring with subsequence length
Counting non-contiguous matches
Off-by-one errors in indexing
4. Identify the bug in the following C++ code snippet for Longest Common Substring:
std::string s1 = "abcde";
std::string s2 = "abfde";
int m = s1.size(), n = s2.size();
std::vector dp(m+1, std::vector<int>(n+1, 0));
int maxLen = 0;
for (int i = 1; i <= m; i++) {
for (int j = 1; j <= n; j++) {
if (s1[i] == s2[j]) {
dp[i][j] = dp[i-1][j-1] + 1;
maxLen = std::max(maxLen, dp[i][j]);
}
}
}
std::cout << maxLen << std::endl;
medium
A. dp vector size should be (m+1) x (n+1) to avoid out-of-bound errors
B. maxLen should be initialized to -1 instead of 0
C. The loop indices should start from 0 instead of 1
D. The comparison should be s1[i-1] == s2[j-1] instead of s1[i] == s2[j]
Solution
Step 1: Check string indexing inside loops
Loop variables i and j start from 1, so to access string characters correctly, indices should be i-1 and j-1.
Step 2: Identify the incorrect comparison
The code compares s1[i] and s2[j], which causes out-of-bound access and wrong comparisons. It should be s1[i-1] == s2[j-1].
Final Answer:
The comparison should be s1[i-1] == s2[j-1] instead of s1[i] == s2[j] -> Option D
Quick Check:
Correct string indexing = i-1 and j-1 [OK]
Hint: Use i-1 and j-1 to index strings when loops start at 1 [OK]
Common Mistakes:
Accessing string with i or j directly causing out-of-bounds
Not initializing dp with correct size
Starting loops at wrong indices
5. Given two strings s1 = "banana" and s2 = "ananas", write a C++ function to find the longest common substring and return it. What is the correct longest common substring?
hard
A. "anana"
B. "nana"
C. "ana"
D. "ban"
Solution
Step 1: Understand the longest common substring candidates
Check substrings common to both strings. "ana" (length 3) appears multiple times in both strings. "anana" is not a substring of both strings contiguously.
Step 2: Verify other options
"nana" length 4 is not a substring of s2; "ban" only in s1; "anana" is not a substring of s2.
Final Answer:
"ana" -> Option C
Quick Check:
Longest common substring between "banana" and "ananas" is "ana" [OK]
Hint: Check all continuous matches, pick longest common substring [OK]
Common Mistakes:
Choosing longest common subsequence instead of substring
Ignoring continuity requirement
Assuming longer substrings without verifying presence
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.