Longest Common Substring ( Space optimized DP solution ) | Space optimized Python3 implementation of longest common substring . ; 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_mat [ 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
import numpy as np NEW_LINE def LCSubStr ( X , Y ) : NEW_LINE INDENT m = len ( X ) NEW_LINE n = len ( Y ) NEW_LINE result = 0 NEW_LINE len_mat = np . zeros ( ( 2 , n ) ) NEW_LINE currRow = 0 NEW_LINE for i in range ( m ) : NEW_LINE INDENT for j in range ( n ) : NEW_LINE INDENT if ( i == 0 j == 0 ) : NEW_LINE INDENT len_mat [ currRow ] [ j ] = 0 NEW_LINE DEDENT elif ( X [ i - 1 ] == Y [ j - 1 ] ) : NEW_LINE INDENT len_mat [ currRow ] [ j ] = len_mat [ 1 - currRow ] [ j - 1 ] + 1 NEW_LINE result = max ( result , len_mat [ currRow ] [ j ] ) NEW_LINE DEDENT else : NEW_LINE INDENT len_mat [ currRow ] [ j ] = 0 NEW_LINE DEDENT DEDENT currRow = 1 - currRow NEW_LINE DEDENT return result NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT X = " GeeksforGeeks " NEW_LINE Y = " GeeksQuiz " NEW_LINE print ( LCSubStr ( X , Y ) ) NEW_LINE DEDENT