JavaScript Program to Find Longest Common Substring Between Two Strings
Last Updated :
21 May, 2024
In this article, we will see how to find the longest common substring between two strings in JavaScript.
A substring is a contiguous sequence of characters within a string. It can be obtained by extracting part of the string starting from any position. We are going to write a JavaScript function that will take two strings and find the common longest consecutive string.
There are two approaches to finding the longest common substring between two strings
Brute-force approach
In this method, we create all possible substrings from both strings and compare them to determine which substring has the longest length in common. The findLongestCommonSubstring() function uses nested loops to generate all possible substrings and compares them to find the longest common substring. In this example, the function findLongestCommonSubstring returns the longest common substring between any two input strings (str1 and str2) given two input strings. In this method time complexity is O(n*m), where n and m are the lengths of the input strings.
Example:
JavaScript
function findLongestCommonSubstring(str1, str2) {
let longestSubstring = "";
for (let i = 0; i < str1.length; i++) {
for (let j = 0; j < str2.length; j++) {
let substring = "";
let x = i;
let y = j;
while (x < str1.length &&
y < str2.length &&
str1[x] === str2[y]) {
substring += str1[x];
x++;
y++;
}
if (substring.length > longestSubstring.length) {
longestSubstring = substring;
}
}
}
return longestSubstring;
}
const string1 = "GeeksForgeeks";
const string2 = "Geekscode";
const longestCommonSubstring =
findLongestCommonSubstring(string1, string2);
console.log("Longest Common Substring:",
longestCommonSubstring);
OutputLongest Common Substring: Geeks
Dynamic Programming
The dynamic programming is the optimised approach of the previous method. In this method we will use 2D array for storing the lengths of common substrings between str1
and str2.
In this example, we are creating an LCS table to store the length of the longest common substring ending at that position. After filling the table by iterating through both strings and incrementing the value if the characters match. Then we keep track of the maximum length seen and the corresponding substring and return the longest substring found.
Example:
JavaScript
function longestCommonSubstring(str1, str2) {
let n = str1.length;
let m = str2.length;
let lcs = [];
for (let i = 0; i <= n; i++) {
lcs[i] = [];
for (let j = 0; j <= m; j++) {
lcs[i][j] = 0;
}
}
let result = "";
let max = 0;
for (let i = 0; i < n; i++) {
for (let j = 0; j < m; j++) {
if (str1[i] === str2[j]) {
lcs[i + 1][j + 1] = lcs[i][j] + 1;
if (lcs[i + 1][j + 1] > max) {
max = lcs[i + 1][j + 1];
result = str1.substring(i - max + 1, i + 1);
}
}
}
}
return result;
}
let str1 = "GeeksForgeeks";
let str2 = "Geekscode";
let result = longestCommonSubstring(str1, str2);
console.log("Longest Common Substring:", result);
OutputLongest Common Substring: Geeks
Using indexOf() and Recursion
To find the longest common substring using indexOf() and recursion, recursively remove characters from the end of each string until a common substring is found. This approach efficiently handles large inputs with overlapping substrings.
Example: In this example the longestCommonSubstring function uses dynamic programming to find the longest common substring between str1 and str2. It returns the identified substring.
JavaScript
function longestCommonSubstring(str1, str2) {
const matrix = Array.from({ length: str1.length + 1 }, () => Array.from({
length: str2.length + 1
}, () => 0));
let longestLength = 0;
let endIndex = 0;
for (let i = 1; i <= str1.length; i++) {
for (let j = 1; j <= str2.length; j++) {
if (str1[i - 1] === str2[j - 1]) {
matrix[i][j] = matrix[i - 1][j - 1] + 1;
if (matrix[i][j] > longestLength) {
longestLength = matrix[i][j];
endIndex = i;
}
}
}
}
return str1.slice(endIndex - longestLength, endIndex);
}
const string1 = "abcdef";
const string2 = "bcde";
console.log(longestCommonSubstring(string1, string2));
Similar Reads
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
JavaScript Tutorial JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. It's an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side: On the client side, Jav
11 min read
Web Development Web development is the process of creating, building, and maintaining websites and web applications. It involves everything from web design to programming and database management. Web development is generally divided into three core areas: Frontend Development, Backend Development, and Full Stack De
5 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
React Interview Questions and Answers React is an efficient, flexible, and open-source JavaScript library that allows developers to create simple, fast, and scalable web applications. Jordan Walke, a software engineer who was working for Facebook, created React. Developers with a JavaScript background can easily develop web applications
15+ min read
Steady State Response In this article, we are going to discuss the steady-state response. We will see what is steady state response in Time domain analysis. We will then discuss some of the standard test signals used in finding the response of a response. We also discuss the first-order response for different signals. We
9 min read
JavaScript Interview Questions and Answers JavaScript (JS) is the most popular lightweight, scripting, and interpreted programming language. JavaScript is well-known as a scripting language for web pages, mobile apps, web servers, and many other platforms. Both front-end and back-end developers need to have a strong command of JavaScript, as
15+ min read
React Tutorial React is a JavaScript Library known for front-end development (or user interface). It is popular due to its component-based architecture, Single Page Applications (SPAs), and Virtual DOM for building web applications that are fast, efficient, and scalable.Applications are built using reusable compon
8 min read
Backpropagation in Neural Network Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read