# Length of largest common subarray in all the rows of given Matrix

• Difficulty Level : Medium
• Last Updated : 23 Jul, 2021

Given a matrix mat[][] of size N×M where each row of the matrix is a permutation of the elements from [1, M], the task is to find the maximum length of the subarray present in each row of the matrix.

Examples:

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.

Input: mat[][] = {{1, 2, 3, 4, 5}, {2, 3, 4, 1, 5}, {5, 2, 3, 4, 1}, {1, 5, 2, 3, 4}}
Output: 3
Explanation:
In each row, {2, 3, 4} is the longest common sub-array present in all the rows of the matrix.

Input: mat[][] = {{4, 5, 1, 2, 3, 6, 7}, {1, 2, 4, 5, 7, 6, 3}, {2, 7, 3, 4, 5, 1, 6}}
Output: 2

Naive Approach: The simplest way to solve the problem is to generate all the possible subarray of the first row of the matrix and then check if the remaining rows contain that sub-array or not.

Time Complexity: O(M×N2)
Auxiliary Space: O(N)

Efficient Approach: The above approach can be optimized by creating a matrix, say dp[][] that stores the position of the element in every row and then check if the current and previous elements index in each row has a difference of 1 or not. Follow the steps below to solve the problem:

• Initialize a matrix, say dp[][] that stores the position of every element in every row.
• To fill the matrix dp[][], Iterate in the range [0, N-1] using the variable i and perform the following steps:
• Initialize variable, say ans that stores the length of the longest sub-array common in all the rows and len that stores the length of the sub-array common in all the rows.
• Iterate in the range [1, M-1] using the variable i and perform the following steps:
• Initialize a boolean variable check as 1, that checks that whether a[i] comes after a[i-1] in each row or not.
• Iterate in the range [1, N-1] using the variable j and perform the following steps:
• If dp[j][arr[i-1]] + 1 != dp[j][arr[i]], modify the value of check as 0 and terminate the loop.
• If the value of the check is 1, then increment the value of len by 1 and modify the value of ans as max(ans, len).
• If the value of the check is 0, then modify the value of len as 1.
• After completing the above steps, print the value of ans as the answer.

Below is the implementation of the above approach:

## C++

 `// C++ program for the above approach``#include ``using` `namespace` `std;` `// Function to find longest common subarray``// in all the rows of the matrix``int` `largestCommonSubarray(``    ``vector > arr,``    ``int` `n, ``int` `m)``{``    ``// Array to store the position``    ``// of element in every row``    ``int` `dp[n][m + 1];` `    ``// Traverse the matrix``    ``for` `(``int` `i = 0; i < n; i++) {``        ``for` `(``int` `j = 0; j < m; j++) {``            ``// Store the position of``            ``// every element in every row``            ``dp[i][arr[i][j]] = j;``        ``}``    ``}` `    ``// Variable to store length of largest``    ``// common Subarray``    ``int` `ans = 1;``    ``int` `len = 1;` `    ``// Traverse through the matrix column``    ``for` `(``int` `i = 1; i < m; i++) {``        ``// Variable to check if every row has``        ``// arr[i][j] next to arr[i-1][j] or not``        ``bool` `check = ``true``;` `        ``// Traverse through the matrix rows``        ``for` `(``int` `j = 1; j < n; j++) {``            ``// Check if arr[i][j] is next to``            ``// arr[i][j-1] in every row or not``            ``if` `(dp[j][arr[i - 1]] + 1``                ``!= dp[j][arr[i]]) {``                ``check = ``false``;``                ``break``;``            ``}``        ``}` `        ``// If every row has arr[j] next``        ``// to arr[j-1] increment len by 1``        ``// and update the value of ans``        ``if` `(check) {``            ``len++;``            ``ans = max(ans, len);``        ``}``        ``else` `{``            ``len = 1;``        ``}``    ``}``    ``return` `ans;``}` `// Driver Code``int` `main()``{` `    ``// Given Input``    ``int` `n = 4;``    ``int` `m = 5;``    ``vector > 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.size();` `    ``// Function Call``    ``cout << largestCommonSubarray(arr, N, M);` `    ``return` `0;``}`

## Java

 `// Java program for the above approach``import` `java.lang.*;``import` `java.util.*;` `class` `GFG{` `// Function to find longest common subarray``// in all the rows of the matrix``static` `int` `largestCommonSubarray(``int``[][] arr,``                                 ``int` `n, ``int` `m)``{``    ` `    ``// Array to store the position``    ``// of element in every row``    ``int` `dp[][] = ``new` `int``[n][m + ``1``];` `    ``// Traverse the matrix``    ``for``(``int` `i = ``0``; i < n; i++)``    ``{``        ``for``(``int` `j = ``0``; j < m; j++)``        ``{``            ` `            ``// Store the position of``            ``// every element in every row``            ``dp[i][arr[i][j]] = j;``        ``}``    ``}` `    ``// Variable to store length of largest``    ``// common Subarray``    ``int` `ans = ``1``;``    ``int` `len = ``1``;` `    ``// Traverse through the matrix column``    ``for``(``int` `i = ``1``; i < m; i++)``    ``{``        ` `        ``// Variable to check if every row has``        ``// arr[i][j] next to arr[i-1][j] or not``        ``boolean` `check = ``true``;` `        ``// Traverse through the matrix rows``        ``for``(``int` `j = ``1``; j < n; j++)``        ``{``            ` `            ``// Check if arr[i][j] is next to``            ``// arr[i][j-1] in every row or not``            ``if` `(dp[j][arr[``0``][i - ``1``]] + ``1` `!=``                ``dp[j][arr[``0``][i]])``            ``{``                ``check = ``false``;``                ``break``;``            ``}``        ``}` `        ``// If every row has arr[j] next``        ``// to arr[j-1] increment len by 1``        ``// and update the value of ans``        ``if` `(check)``        ``{``            ``len++;``            ``ans = Math.max(ans, len);``        ``}``        ``else``        ``{``            ``len = ``1``;``        ``}``    ``}``    ``return` `ans;``}` `// Driver code``public` `static` `void` `main(String[] args)``{``    ` `    ``// Given Input``    ``int` `n = ``4``;``    ``int` `m = ``5``;``    ``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.length;``    ``int` `M = arr[``0``].length;` `    ``// Function Call``    ``System.out.println(largestCommonSubarray(arr, N, M));``}``}` `// This code is contributed by avijitmondal1998`

## Python3

 `# Python3 program for the above approach` `# Function to find longest common subarray``# in all the rows of the matrix``def` `largestCommonSubarray(arr, n, m):``  ` `    ``# Array to store the position``    ``# of element in every row``    ``dp ``=` `[[``0` `for` `i ``in` `range``(m``+``1``)] ``for` `j ``in` `range``(n)]` `    ``# Traverse the matrix``    ``for` `i ``in` `range``(n):``        ``for` `j ``in` `range``(m):``          ` `            ``# Store the position of``            ``# every element in every row``            ``dp[i][arr[i][j]] ``=` `j` `    ``# Variable to store length of largest``    ``# common Subarray``    ``ans ``=` `1``    ``len1 ``=` `1` `    ``# Traverse through the matrix column``    ``for` `i ``in` `range``(``1``,m,``1``):``        ``# Variable to check if every row has``        ``# arr[i][j] next to arr[i-1][j] or not``        ``check ``=` `True` `        ``# Traverse through the matrix rows``        ``for` `j ``in` `range``(``1``,n,``1``):``            ``# Check if arr[i][j] is next to``            ``# arr[i][j-1] in every row or not``            ``if` `(dp[j][arr[``0``][i ``-` `1``]] ``+` `1` `!``=` `dp[j][arr[``0``][i]]):``                ``check ``=` `False``                ``break``            ` `        ``# If every row has arr[j] next``        ``# to arr[j-1] increment len by 1``        ``# and update the value of ans``        ``if` `(check):``            ``len1 ``+``=` `1``            ``ans ``=` `max``(ans, len1)` `        ``else``:``            ``len1 ``=` `1` `    ``return` `ans` `# Driver Code``if` `__name__ ``=``=` `'__main__'``:``  ` `    ``# Given Input``    ``n ``=` `4``    ``m ``=` `5``    ``arr ``=` `[[``4``, ``5``, ``1``, ``2``, ``3``, ``6``, ``7``],``           ``[``1``, ``2``, ``4``, ``5``, ``7``, ``6``, ``3``],``           ``[``2``, ``7``, ``3``, ``4``, ``5``, ``1``, ``6``]]` `    ``N ``=` `len``(arr)``    ``M ``=` `len``(arr[``0``])` `    ``# Function Call``    ``print``(largestCommonSubarray(arr, N, M))``    ` `    ``# This code is contributed by bgangwar59.`

## Javascript

 ``

## C#

 `// C# program for the above approach``using` `System;``using` `System.Collections.Generic;` `class` `GFG{` `// Function to find longest common subarray``// in all the rows of the matrix``static` `int` `largestCommonSubarray(``int` `[,]arr,``                                 ``int` `n, ``int` `m)``{``    ` `    ``// Array to store the position``    ``// of element in every row``    ``int` `[,]dp = ``new` `int``[n,m + 1];` `    ``// Traverse the matrix``    ``for``(``int` `i = 0; i < n; i++)``    ``{``        ``for``(``int` `j = 0; j < m; j++)``        ``{``            ` `            ``// Store the position of``            ``// every element in every row``            ``dp[i,arr[i,j]] = j;``        ``}``    ``}` `    ``// Variable to store length of largest``    ``// common Subarray``    ``int` `ans = 1;``    ``int` `len = 1;` `    ``// Traverse through the matrix column``    ``for``(``int` `i = 1; i < m; i++)``    ``{``        ` `        ``// Variable to check if every row has``        ``// arr[i][j] next to arr[i-1][j] or not``        ``bool` `check = ``true``;` `        ``// Traverse through the matrix rows``        ``for``(``int` `j = 1; j < n; j++)``        ``{``            ` `            ``// Check if arr[i][j] is next to``            ``// arr[i][j-1] in every row or not``            ``if` `(dp[j,arr[0,i - 1]] + 1 !=``                ``dp[j,arr[0,i]])``            ``{``                ``check = ``false``;``                ``break``;``            ``}``        ``}` `        ``// If every row has arr[j] next``        ``// to arr[j-1] increment len by 1``        ``// and update the value of ans``        ``if` `(check == ``true``)``        ``{``            ``len++;``            ``ans = Math.Max(ans, len);``        ``}``        ``else``        ``{``            ``len = 1;``        ``}``    ``}``    ``return` `ans;``}` `// Driver code``public` `static` `void` `Main()``{``    ` `    ``// Given Input``    ``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 = 3;``    ``int` `M = 7;` `    ``// Function Call``    ``Console.Write(largestCommonSubarray(arr, N, M));``}``}` `// This code is contributed by _saurabh_jaiswal.`
Output
`2`

Time Complexity: O(N×M)
Auxiliary Space: O(N×M)

My Personal Notes arrow_drop_up