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 ; Given Input ; Function Call
function largestCommonSubarray ( arr , n , m ) { let dp = Array ( n ) . fill ( ) . map ( ( ) => Array ( m + 1 ) ) ; for ( let i = 0 ; i < n ; i ++ ) { for ( let j = 0 ; j < m ; j ++ ) { dp [ i ] [ arr [ i ] [ j ] ] = j ; } } let ans = 1 ; let len = 1 ; for ( let i = 1 ; i < m ; i ++ ) { let check = true ; for ( let j = 1 ; j < n ; j ++ ) { if ( dp [ j ] [ arr [ 0 ] [ i - 1 ] ] + 1 != dp [ j ] [ arr [ 0 ] [ i ] ] ) { check = false ; break ; } } if ( check ) { len ++ ; ans = Math . max ( ans , len ) ; } else { len = 1 ; } } return ans ; } let n = 4 ; let m = 5 ; let arr = [ [ 4 , 5 , 1 , 2 , 3 , 6 , 7 ] , [ 1 , 2 , 4 , 5 , 7 , 6 , 3 ] , [ 2 , 7 , 3 , 4 , 5 , 1 , 6 ] ] ; let N = arr . length ; let M = arr [ 0 ] . length ; document . write ( largestCommonSubarray ( arr , N , M ) ) ;