The Wayback Machine - https://web.archive.org/web/20240822185354/https://www.geeksforgeeks.org/javascript-program-to-find-longest-common-substring-between-two-strings/
Open In App

JavaScript Program to Find Longest Common Substring Between Two Strings

Last Updated : 21 May, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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);

Output
Longest 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);

Output
Longest 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)); 

Output
bcde


Similar Reads

Javascript Program To Find Length Of The Longest Substring Without Repeating Characters
Given a string str, find the length of the longest substring without repeating characters.  For “ABDEFGABEF”, the longest substring are “BDEFGA” and "DEFGAB", with length 6.For “BBBB” the longest substring is “B”, with length 1.For "GEEKSFORGEEKS", there are two longest substrings shown in the below diagrams, with length 7 The desired time complexi
5 min read
Javascript Program To Find Longest Common Prefix Using Sorting
Problem Statement: Given a set of strings, find the longest common prefix.Examples: Input: {"geeksforgeeks", "geeks", "geek", "geezer"} Output: "gee" Input: {"apple", "ape", "april"} Output: "ap" The longest common prefix for an array of strings is the common prefix between 2 most dissimilar strings. For example, in the given array {"apple", "ape",
2 min read
Javascript Program To Find Longest Common Prefix Using Word By Word Matching
Given a set of strings, find the longest common prefix. Examples: Input : {“geeksforgeeks”, “geeks”, “geek”, “geezer”} Output : "gee" Input : {"apple", "ape", "april"} Output : "ap" Recommended: Please solve it on “PRACTICE ” first, before moving on to the solution. We start with an example. Suppose there are two strings- “geeksforgeeks” and “geeks
3 min read
JavaScript Program to Find Common Elements Between Two Sorted Arrays using Binary Search
Given two sorted arrays, our task is to find common elements in two sorted arrays then the program should return an array that contains all the elements that are common to the two arrays. The arrays can contain duplicate elements, that is, values at one index in an array can be equal to the values at another index in the array. Example: Input: arr1
3 min read
JavaScript Program for Longest Common Subsequence
The longest common subsequence (LCS) is defined as the longest subsequence which is common in all given input sequences. In this article, we are given two strings, String1 and String2, the task is to find the longest common subsequence in both of the strings. A subsequence of a string can be achieved by deleting any number of elements from the stri
6 min read
How to get a substring between two strings in PHP?
To get a substring between two strings there are few popular ways to do so. Below the procedures are explained with the example.Examples: Input:$string="hey, How are you?"If we need to extract the substring between "How" and "you" then the output should be are Output:"Are"Input:Hey, Welcome to GeeksforGeeksIf we need to get the substring between We
5 min read
JavaScript Program to Find Uncommon Characters of the two Strings
In JavaScript, finding uncommon characters in two strings is the process of identifying the characters that exist in one string but not in the other string. We can find these uncommon characters using various approaches that are mentioned below: Table of Content Using SetsUsing Array.filter() methodUsing Logical OR OperationUsing SetsIn this approa
2 min read
Find the common elements of more than two JavaScript arrays ?
Given an HTML document having multiple arrays with some elements and the task is to get the common elements from arrays with the help of JavaScript. There are two approaches that are discussed below. Approach 1: First get the arrays in 2-dimensional format then take the first array by shift() method and then filter out the elements from the first a
3 min read
How to Find if Two Arrays Contain any Common Item in JavaScript?
JavaScript Array is a single variable that is used to store elements of different data types. JavaScript arrays are zero-indexed. So, we are given two arrays containing array elements and the task is to check if two arrays contain any common elements then it returns True otherwise returns False. Examples: Input: array1 = ['a', 'b', 'c', 'd', 'e'] a
7 min read
Check an array of strings contains a substring in JavaScript
Checking if an array of strings contains a substring in JavaScript involves iterating through each string in the array and examining if the substring exists within any of them. This process ensures efficient detection of the substring's presence within the array. These are the following ways to do this: Table of Content Using includes() method and
4 min read
JavaScript Program to find the Index of the First Occurrence of a Substring in a String
In this article, we will find the index of the first occurrence of a substring in a string using JavaScript. An essential task in JavaScript programming is searching for substrings within a string. Finding the index of the first occurrence of a substring is a typical necessity, whether you are constructing a website, working with data processing, o
6 min read
JavaScript Program to Find the Index of the Last Occurrence of a Substring in a String
Finding the index of the last occurrence of a substring in a string is a common task in JavaScript. The last occurrence of a substring in a string in JavaScript refers to finding the final position where a specified substring appears within a given string. We may want to know the position of the last occurrence of a specific substring within a give
5 min read
Javascript Program For Comparing Two Strings Represented As Linked Lists
Given two strings, represented as linked lists (every character is a node in a linked list). Write a function compare() that works similar to strcmp(), i.e., it returns 0 if both strings are the same, 1 if the first linked list is lexicographically greater, and -1 if the second string is lexicographically greater.Examples: Input: list1 = g-&gt;e-
2 min read
Javascript Program To Check Whether Two Strings Are Anagram Of Each Other
Write a function to check whether two given strings are anagram of each other or not. An anagram of a string is another string that contains the same characters, only the order of characters can be different. For example, "abcd" and "dabc" are an anagram of each other. We strongly recommend that you click here and practice it, before moving on to t
7 min read
JavaScript Program to Compare Two Strings Lexicographically
This JavaScript program compares two strings lexicographically, meaning it checks if one string comes before or after the other in alphabetical order. Lexicographical comparison is based on the Unicode value of each character in the strings. The program should return a positive value if the first string comes after the second string, a negative val
2 min read
JavaScript Program to Add Two Binary Strings
In this article, we will see the addition operation on two binary Strings in JavaScript. The addition of two binary strings in JavScript is the concept of performing binary addition on a collection of two binary strings, treating them as binary numbers (1 or 0), and then printing the sum of the binary representation as the final result. Table of Co
5 min read
JavaScript Program to Compare Two Strings
In JavaScript, comparing two strings can be essential for performing tasks like user authentication. It can involve checking if the user has entered the same credentials as there are in the database. This article provides insights into comparing two strings in JavaScript. It explores four distinct approaches with detailed explanations and examples.
3 min read
JavaScript Program to Check if Two Strings are Same or Not
In this article, we are going to implement a JavaScript program to check whether two strings are the same or not. If they are the same then we will return true else we will return false. Examples: Input: str1 = Geeks, str2 = GeeksOutput: True. Strings are the SameInput: str1 = Geeks, str2 = GeekOutput: False. Strings are not SameTable of Content Us
4 min read
JavaScript Program to find the Longest Consecutive Sequence of Numbers in an Array
In this article, we are going to find the longest consecutive sequence of numbers in an array using JavaScript language. We are given an array that consists of integers we need to find the longest subsequence such that elements in the subsequence are consecutive integers, these numbers are in any order. Example: Input: inputArray[] = [1, 9, 3, 10,
4 min read
Javascript Program to Find the Longest Bitonic Subsequence | DP-15
Given an array arr[0 ... n-1] containing n positive integers, a subsequence of arr[] is called Bitonic if it is first increasing, then decreasing. Write a function that takes an array as argument and returns the length of the longest bitonic subsequence. A sequence, sorted in increasing order is considered Bitonic with the decreasing part as empty.
3 min read
JavaScript Program to Find the length of the Longest Continuous Decreasing Subarray
Given an array of numbers, our task is to find the length of the longest continuous subarray where the numbers are strictly decreasing. Example: Input:const arr = [7, 4, 7, 6, 5, 4, 6, 8, 9]Output: 4Explanation: The longest continuous decreasing subarray in this array is [7, 6, 5, 4], and its length is 4.Below are the approaches to Find the length
3 min read
JavaScript Program to Find the Length of Longest Balanced Subsequence
In this article, we are going to learn about the Length of the Longest Balanced Subsequence in JavaScript. The Length of the Longest Balanced Subsequence refers to the maximum number of characters in a string sequence that can form a valid balanced expression, consisting of matching opening and closing brackets. Example: Input : S = "()())"Output :
4 min read
How to calculate greatest common divisor of two or more numbers/arrays in JavaScript ?
In this article, we are given two or more numbers/array of numbers and the task is to find the GCD of the given numbers/array elements in JavaScript. Examples: Input : arr[] = {1, 2, 3} Output : 1 Input : arr[] = {2, 4, 6, 8} Output : 2 The GCD of three or more numbers equals the product of the prime factors common to all the numbers, but it can al
2 min read
How To Find The Most Recent Common Ancestor of Two Branches in Git?
In software development, managing code changes through version control systems is crucial. Git, one of the most popular version control systems, allows developers to create branches for features, bug fixes, or experiments. These branches can diverge from the main codebase and evolve independently. Eventually, you may need to find the most recent co
3 min read
Replace multiple strings with multiple other strings in JavaScript
In this article, we are given a Sentence having multiple strings. The task is to replace multiple strings with new strings simultaneously instead of doing it one by one, using JavaScript. Below are a few methods to understand: Table of Content Using JavaScript replace() method Using the JavaScript str.replaceAll() methodUsing Array.reduce() method:
2 min read
JavaScript Program to Find Shortest Distance Between Two Words in an Array of Words
Given an array of words and two target words, the task is to find the shortest distance (minimum number of words) between the two target words in the array. The distance is calculated by counting the number of words between the two target words, excluding the target words themselves. Approaches to find the shortest distance between two wordsTable o
2 min read
Javascript Program to Find difference between sums of two diagonals
Given a matrix of n X n. The task is to calculate the absolute difference between the sums of its diagonal.Examples: Input : mat[][] = 11 2 4 4 5 6 10 8 -12 Output : 15 Sum of primary diagonal = 11 + 5 + (-12) = 4. Sum of primary diagonal = 4 + 5 + 10 = 19. Difference = |19 - 4| = 15. Input : mat[][] = 10 2 4 5 Output : 7 Recommended: Please solve
3 min read
JavaScript Program to Find the Distance Value between Two Arrays
We will be given two integer arrays and an integer d. The task is to calculate the distance between the two given arrays based on the given integer value. The distance value will be calculated as the number of elements arr1[i] such that there is not any element arr2[j] where |arr1[i]-arr2[j]| &lt;= d. Example:Input: arr1 = [4, 5, 8], arr2 = [10, 9,
3 min read
JavaScript Program to Find the Sum of Elements Between Two Given Indices in an Array
In JavaScript programming, there are often scenarios where we need to calculate the sum of elements within a specific range in an array. This can be useful in various applications, such as calculating subarray sums in algorithms or performing range-based calculations in data analysis. Example: Input: const array = [1, 2, 3, 4, 5];const startIndex =
3 min read
JavaScript Program to find Maximum Distance Between two Occurrences of Same Element in Array
Given an array of repeated elements, the task is to find the maximum distance between two occurrences of an element. Example: Input : arr[] = {3, 2, 1, 2, 1, 4, 5, 8, 6, 7, 4, 2}Output: 10// maximum distance for 2 is 11-1 = 10 // maximum distance for 1 is 4-2 = 2 // maximum distance for 4 is 10-5 = 5 Table of Content Method 1: Brute force:Method 2:
3 min read
three90RightbarBannerImg