Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on DP
  • Practice DP
  • MCQs on DP
  • Tutorial on Dynamic Programming
  • Optimal Substructure
  • Overlapping Subproblem
  • Memoization
  • Tabulation
  • Tabulation vs Memoization
  • 0/1 Knapsack
  • Unbounded Knapsack
  • Subset Sum
  • LCS
  • LIS
  • Coin Change
  • Word Break
  • Egg Dropping Puzzle
  • Matrix Chain Multiplication
  • Palindrome Partitioning
  • DP on Arrays
  • DP with Bitmasking
  • Digit DP
  • DP on Trees
  • DP on Graph
Open In App
Next Article:
Row-wise common elements in two diagonals of a square matrix
Next article icon

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

Last Updated : 23 Jul, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

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:

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:
    • Iterate in the range[0, M-1] using the variable j and modify the value of dp[i][arr[i][j]] as j.
  • 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][0] comes after a[i-1][0] 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[0][i-1]] + 1 != dp[j][arr[0][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 <bits/stdc++.h> using namespace std;  // Function to find longest common subarray // in all the rows of the matrix int largestCommonSubarray(     vector<vector<int> > 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[0][i - 1]] + 1                 != dp[j][arr[0][i]]) {                 check = false;                 break;             }         }          // If every row has arr[0][j] next         // to arr[0][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<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();      // 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[0][j] next         // to arr[0][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[0][j] next         # to arr[0][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
  <script>         // JavaScript program for the above approach          // Function to find longest common subarray         // in all the rows of the matrix         function largestCommonSubarray(arr, n, m) {             // Array to store the position             // of element in every row             let dp = Array(n).fill().map(() => Array(m + 1));              // Traverse the matrix             for (let i = 0; i < n; i++) {                 for (let 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             let ans = 1;             let len = 1;              // Traverse through the matrix column             for (let i = 1; i < m; i++) {                 // Variable to check if every row has                 // arr[i][j] next to arr[i-1][j] or not                 let check = true;                  // Traverse through the matrix rows                 for (let 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[0][j] next                 // to arr[0][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           // Given Input         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;          // Function Call         document.write(largestCommonSubarray(arr, N, M));      // This code is contributed by Potta Lokesh      </script> 
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[0][j] next         // to arr[0][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)


Next Article
Row-wise common elements in two diagonals of a square matrix

P

parthagarwal1962000
Improve
Article Tags :
  • Dynamic Programming
  • Matrix
  • Competitive Programming
  • DSA
  • subarray
Practice Tags :
  • Dynamic Programming
  • Matrix

Similar Reads

  • Minimum common element in subarrays of all possible lengths
    Given an array arr[] consisting of N integers from the range [1, N]( repetition allowed ), the task is to find the minimum common element for each possible subarray length. If no such element exists for any particular length of the subarray, then print -1. Examples: Input: arr[] = {1, 3, 4, 5, 6, 7}
    11 min read
  • Find a common element in all rows of a given row-wise sorted matrix
    Given a matrix where every row is sorted in increasing order. Write a function that finds and returns a common element in all rows. If there is no common element, then returns -1. Example: Input: mat[4][5] = { {1, 2, 3, 4, 5}, {2, 4, 5, 8, 10}, {3, 5, 7, 9, 11}, {1, 3, 5, 7, 9}, };Output: 5A O(m*n*n
    15+ min read
  • Maximum GCD of all subarrays of length at least 2
    Given an array arr[] of N numbers. The task is to find the maximum GCD of all subarrays of size greater than 1. Examples: Input: arr[] = { 3, 18, 9, 9, 5, 15, 8, 7, 6, 9 } Output: 9 Explanation: GCD of the subarray {18, 9, 9} is maximum which is 9.Input: arr[] = { 4, 8, 12, 16, 20, 24 } Output: 4 Ex
    5 min read
  • Longest common subarray in the given two arrays
    Given two arrays A[] and B[] of N and M integers respectively, the task is to find the maximum length of an equal subarray or the longest common subarray between the two given array. Examples: Input: A[] = {1, 2, 8, 2, 1}, B[] = {8, 2, 1, 4, 7} Output: 3 Explanation: The subarray that is common to b
    15+ min read
  • Row-wise common elements in two diagonals of a square matrix
    Given a square matrix, find out count of numbers that are same in same row and same in both primary and secondary diagonals. Examples : Input : 1 2 1 4 5 2 0 5 1 Output : 2 Primary diagonal is 1 5 1 Secondary diagonal is 1 5 0 Two elements (1 and 5) match in two diagonals and same. Input : 1 0 0 0 1
    4 min read
  • Find distinct elements common to all rows of a matrix
    Given a n x n matrix. The problem is to find all the distinct elements common to all rows of the matrix. The elements can be printed in any order. Examples: Input : mat[][] = { {2, 1, 4, 3}, {1, 2, 3, 2}, {3, 6, 2, 3}, {5, 2, 5, 3} } Output : 2 3 Input : mat[][] = { {12, 1, 14, 3, 16}, {14, 2, 1, 3,
    15+ min read
  • Length of the largest subarray with contiguous elements | Set 2
    Given an array of integers, find length of the longest subarray which contains numbers that can be arranged in a continuous sequence. In the previous post, we have discussed a solution that assumes that elements in given array are distinct. Here we discuss a solution that works even if the input arr
    7 min read
  • Length of the largest subarray with contiguous elements | Set 1
    Given an array of distinct integers, find length of the longest subarray which contains numbers that can be arranged in a continuous sequence. Examples: Input: arr[] = {10, 12, 11}; Output: Length of the longest contiguous subarray is 3 Input: arr[] = {14, 12, 11, 20}; Output: Length of the longest
    7 min read
  • Common elements in all rows of a given matrix
    Given an m x n matrix, find all common elements present in all rows in O(mn) time and one traversal of matrix. Example: Input:mat[4][5] = {{1, 2, 1, 4, 8}, {3, 7, 8, 5, 1}, {8, 7, 7, 3, 1}, {8, 1, 2, 7, 9}, };Output: 1 8 or 8 18 and 1 are present in all rows.A simple solution is to consider every el
    7 min read
  • Find the length of Longest increasing Consecutive Subarray
    Given an array arr[] of N integers, the task is to find the length of the longest increasing subarray such that elements in the subarray are consecutive integers. Examples: Input: arr[] = {1, 9, 3, 4, 20, 2}Output: 2Explanation: The subarray {3, 4} is the longest subarray of consecutive elements Inp
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences