Longest Common Substring ( Space optimized DP solution ) | Function to find longest common substring . ; Find length of both the strings . ; Variable to store length of longest common substring . ; Matrix to store result of two consecutive rows at a time . ; Variable to represent which row of matrix is current row . ; For a particular value of i and j , len [ currRow ] [ j ] stores length of longest common substring in string X [ 0. . i ] and Y [ 0. . j ] . ; Make current row as previous row and previous row as new current row . ; Driver code
function LCSubStr ( X , Y ) { var m = X . length ; var n = Y . length ; var result = 0 ; var len = Array . from ( Array ( 2 ) , ( ) => Array ( n ) ) ; var currRow = 0 ; for ( var i = 0 ; i <= m ; i ++ ) { for ( var j = 0 ; j <= n ; j ++ ) { if ( i == 0 j == 0 ) { len [ currRow ] [ j ] = 0 ; } else if ( X [ i - 1 ] == Y [ j - 1 ] ) { len [ currRow ] [ j ] = len [ 1 - currRow ] [ j - 1 ] + 1 ; result = Math . max ( result , len [ currRow ] [ j ] ) ; } else { len [ currRow ] [ j ] = 0 ; } } currRow = 1 - currRow ; } return result ; } var X = " " ; var Y = " " ; document . write ( LCSubStr ( X , Y ) ) ;