JavaScript Program to Find Longest Common Substring Between Two Strings Last Updated : 21 May, 2024 Comments Improve Suggest changes Like Article Like Report 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 Table of Content Brute-force approachDynamic ProgrammingUsing indexOf() and RecursionBrute-force approachIn 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 ProgrammingThe 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 RecursionTo 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)); Outputbcde Comment More infoAdvertise with us Next Article JavaScript Program to Find Longest Common Substring Between Two Strings P pranay0911 Follow Improve Article Tags : JavaScript Web Technologies javascript-string JavaScript-DSA JavaScript-Program +1 More Similar Reads JavaScript Program for Printing Shortest Common Supersequence A Shortest Common Supersequence (SCS) is the shortest or smallest string that contains two given strings as a subsequence. It is a minimal combination of characters that includes all elements of both input strings. In this article, we will see different approaches for printing the shortest common su 8 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"We start with an example. Suppose there are two strings- âgeeksforgeeksâ and âgeeksâ. What is the longest common prefix in 3 min read 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 5 min read How to Find the Longest Common Prefix of Two Strings in Java? In this article, we will find the longest common prefix of two Strings in Java. Examples: Input: String 1= geeksforgeeks, String 2 = geezerOutput: âgeeâ Input: String 1= flower, String 2 = flightOutput: âflâ Methods to Find the Longest common Prefix of two Strings in JavaBelow are the methods by whi 4 min read How to Split a String into Equal Length Substrings in Java? In Java, splitting a string into smaller substrings of equal length is useful for processing large strings in manageable pieces. We can do this with the substring method of the loop. This method extracts a substring of the specified length from the input string and stores it in a list.Example:In the 3 min read Program to find the Length of the longest substring without repeating characters in Golang Given a string, print the longest substring without repeating characters in Golang. For example, the longest substrings without repeating characters for âABDEFGABEFâ are âBDEFGAâ. Examples: Input : GEEKSFORGEEKS Output : Substring: EKSFORG Length: 7 Input : ABDEFGABEF Output : Substring: BDEFGA Leng 4 min read Find the Longest Non-Prefix-Suffix Substring in the Given String Given a string s of length n. The task is to determine the longest substring t such that t is neither the prefix nor the suffix of string s, and that substring must appear as both prefix and suffix of the string s. If no such string exists, print -1. Example: Input: s = "fixprefixsuffix"Output: fix 7 min read How to Calculate the Levenshtein Distance Between Two Strings in Java Using Recursion? In Java, the Levenshtein Distance Algorithm is a pre-defined method used to measure the similarity between two strings and it can be used to calculate the minimum number of single-character edits (inserts, deletions, or substitutions) required to change one string into another. Prerequisites: Recurs 4 min read Find the LCS of string such that it does not contains the given string Given three strings s1, s2 and s3. The task is to compute the Longest Common Subsequence of the string s1 and s2, such that it does not contain s3 as a substring. If there is no valid common subsequence, output -1. Examples: Input: s1 = "AJKEQSLOBSROFGZ", s2 = "OVGURWZLWVLUXTH", s3 = "OZ"Output: ORZ 11 min read Java Program to Implement Wagner and Fisher Algorithm for Online String Matching The Wagner-Fischer Algorithm is a dynamic programming algorithm that measures the Levenshtein distance or the edit distance between two strings of characters. Levenshtein Distance(LD) calculates how similar are the two strings. The distance is calculated by three parameters to transform the string1 3 min read Like