Length of largest common subarray in all the rows of given Matrix | C ++ program for the above approach ; 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; int largestCommonSubarray ( vector < vector < int > > arr , int n , int m ) { int dp [ n ] [ m + 1 ] ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j < m ; j ++ ) { dp [ i ] [ arr [ i ] [ j ] ] = j ; } } int ans = 1 ; int len = 1 ; for ( int i = 1 ; i < m ; i ++ ) { bool check = true ; for ( int 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 = max ( ans , len ) ; } else { len = 1 ; } } return ans ; } int main ( ) { int n = 4 ; int m = 5 ; vector < vector < int > > arr { { 4 , 5 , 1 , 2 , 3 , 6 , 7 } , { 1 , 2 , 4 , 5 , 7 , 6 , 3 } , { 2 , 7 , 3 , 4 , 5 , 1 , 6 } } ; int N = arr . size ( ) ; int M = arr [ 0 ] . size ( ) ; cout << largestCommonSubarray ( arr , N , M ) ; return 0 ; }