Length of largest common subarray in all the rows of given Matrix | Function to find longest common subarray in all the rows of the matrix ; Array to store the position of element in every row ; Traverse the matrix ; Store the position of every element in every row ; Variable to store length of largest common Subarray ; Traverse through the matrix column ; Variable to check if every row has arr [ i ] [ j ] next to arr [ i - 1 ] [ j ] or not ; Traverse through the matrix rows ; Check if arr [ i ] [ j ] is next to arr [ i ] [ j - 1 ] in every row or not ; If every row has arr [ 0 ] [ j ] next to arr [ 0 ] [ j - 1 ] increment len by 1 and update the value of ans ; Driver Code ; Given Input ; Function Call
def largestCommonSubarray ( arr , n , m ) : NEW_LINE INDENT dp = [ [ 0 for i in range ( m + 1 ) ] for j in range ( n ) ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( m ) : NEW_LINE INDENT dp [ i ] [ arr [ i ] [ j ] ] = j NEW_LINE DEDENT DEDENT ans = 1 NEW_LINE len1 = 1 NEW_LINE for i in range ( 1 , m , 1 ) : NEW_LINE INDENT check = True NEW_LINE for j in range ( 1 , n , 1 ) : NEW_LINE INDENT if ( dp [ j ] [ arr [ 0 ] [ i - 1 ] ] + 1 != dp [ j ] [ arr [ 0 ] [ i ] ] ) : NEW_LINE INDENT check = False NEW_LINE break NEW_LINE DEDENT DEDENT if ( check ) : NEW_LINE INDENT len1 += 1 NEW_LINE ans = max ( ans , len1 ) NEW_LINE DEDENT else : NEW_LINE INDENT len1 = 1 NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 4 NEW_LINE m = 5 NEW_LINE arr = [ [ 4 , 5 , 1 , 2 , 3 , 6 , 7 ] , [ 1 , 2 , 4 , 5 , 7 , 6 , 3 ] , [ 2 , 7 , 3 , 4 , 5 , 1 , 6 ] ] NEW_LINE N = len ( arr ) NEW_LINE M = len ( arr [ 0 ] ) NEW_LINE print ( largestCommonSubarray ( arr , N , M ) ) NEW_LINE DEDENT