Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Finding the longest common consecutive substring between two strings in JavaScript
We are required to write a JavaScript function that takes in two strings. Let's call them str1 and str2. The function should then find out the longest consecutive string that is common to both the input strings and return that common string.
For example ?
If the input strings are ?
const str1 = 'ABABC'; const str2 = 'BABCA';
Then the output string should be ?
const output = 'BABC';
How It Works
This problem uses dynamic programming to build a 2D matrix where each cell [i][j] represents the length of the common substring ending at position i in str2 and position j in str1. When characters match, we extend the previous diagonal length by 1. When they don't match, we reset to 0.
Example
Following is the code ?
const str1 = 'ABABC';
const str2 = 'BABCA';
const findCommon = (str1 = '', str2 = '') => {
const s1 = [...str1];
const s2 = [...str2];
const arr = Array(s2.length + 1).fill(null).map(() => {
return Array(s1.length + 1).fill(null);
});
for (let j = 0; j <= s1.length; j += 1) {
arr[0][j] = 0;
}
for (let i = 0; i <= s2.length; i += 1) {
arr[i][0] = 0;
}
let len = 0;
let col = 0;
let row = 0;
for (let i = 1; i <= s2.length; i += 1) {
for (let j = 1; j <= s1.length; j += 1) {
if (s1[j - 1] === s2[i - 1]) {
arr[i][j] = arr[i - 1][j - 1] + 1;
}
else {
arr[i][j] = 0;
}
if (arr[i][j] > len) {
len = arr[i][j];
col = j;
row = i;
}
}
}
if (len === 0) {
return '';
}
let res = '';
while (arr[row][col] > 0) {
res = s1[col - 1] + res;
row -= 1;
col -= 1;
}
return res;
};
console.log(findCommon(str1, str2));
Output
Following is the output on console ?
BABC
Alternative Approach Using Nested Loops
Here's a simpler approach that directly compares all possible substrings:
const findLongestCommonSubstring = (str1, str2) => {
let longest = '';
for (let i = 0; i < str1.length; i++) {
for (let j = i + 1; j <= str1.length; j++) {
let substring = str1.slice(i, j);
if (str2.includes(substring) && substring.length > longest.length) {
longest = substring;
}
}
}
return longest;
};
console.log(findLongestCommonSubstring('ABABC', 'BABCA'));
console.log(findLongestCommonSubstring('GeeksforGeeks', 'GeeksQuiz'));
BABC Geeks
Comparison
| Method | Time Complexity | Space Complexity | Readability |
|---|---|---|---|
| Dynamic Programming | O(m×n) | O(m×n) | Complex |
| Nested Loops | O(m×n²) | O(1) | Simple |
Conclusion
The dynamic programming approach is more efficient for large strings, while the nested loop method is simpler to understand. Choose based on your performance requirements and code complexity preferences.
