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:
Submatrix of given size with maximum 1's
Next article icon

Largest possible square submatrix with maximum AND value

Last Updated : 30 May, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an integer matrix mat [ ][ ] dimensions, the task is to find the largest possible square matrix from the given matrix with maximum AND value. 

AND value of a matrix is defined as the value obtained after performing bitwise AND operation on all elements of the matrix. 
 

Examples: 

Input: mat [ ][ ] = {{2, 3, 3}, {2, 3, 3}, {2, 2, 2}} 
Output: 4 
Explanation: 
Given square submatrix has AND value 2. 
The submatrix 
{{3, 3} 
{3, 3}} 
of size 4 has maximum AND value 3. All other square submatrices of size 4 have AND value 2.

Input: mat [ ][ ] = 
{{9, 9, 9, 8}, 
{9, 9, 9, 6}, 
{9, 9, 9, 3}, 
{2, 2, 2, 2}} 
Output: 9 
Explanation: 
The submatrix of size 9 
{{9, 9, 9}, 
{9, 9, 9}, 
{9, 9, 9}} 
have maximum AND value 9. 
 

Naive Approach: 
Generate all square submatrices from the given matrix. Initialize a variable answer to store the maximum & value for submatrices and another variable count to store the number of elements in the submatrix. Print the maximum value of count corresponding to maximum AND value answer obtained from all square submatrices.

Efficient Approach: 
Follow the steps below to optimize the above solution: 

  • To maximize the & value, we need to find a submatrix that consists only of the maximum element in the matrix. This is because the maximum possible AND value in the matrix is the maximum element present in the matrix.
  • Find the maximum possible value present in the matrix.
  • Use Dynamic programming approach to get maximum size submatrix filled by the maximum matrix element only.
  • Create an auxiliary dp[][] such that dp[i][j] stores the largest possible square submatrix mat[i][j] can be a part of such that the AND value of that submatrix is equal to mat[i][j].
  • The recurrence relation is as follows:

If mat[i][j] is equal to {mat[i-1][j], mat[i][j-1], mat[i-1][j-1]} then consider all the three values as a square submatrix and update DP[i][j] as: 
DP[i][j] = min(DP[i-1][j], DP[i][j-1], DP[i-1][j-1]) + 1 
Otherwise, 
DP[i][j] = 1 
The answer would be the maximum of all DP [i][j] 
 

  • Finally, iterate over the dp[][] matrix and find the largest dp[i][j] for every mat[i][j] equal to the maximum element in the array.

Below is implementation of above approach:  

C++
// C++ program to find  // the length of longest  // possible square submatrix  // with maximum AND value  // from the given matrix  #include <bits/stdc++.h>  using namespace std;   // Function to calculate and  // return the length of  // square submatrix with  // maximum AND value  int MAX_value(vector<vector<int> > arr)  {      // Extract dimensions      int row = arr.size();      int col = arr[0].size();       // Auxiliary array      int dp[row][col];       // Initialize auxiliary array      memset(dp, sizeof(dp), 0);       // c: Stores the maximum      // value in the matrix      // p: Stores the number      // of elements in the      // submatrix having      // maximum AND value      int i = 0, j = 0;      int c = arr[0][0], p = 0;      int d = row;       // Iterate over the matrix      // to fill the auxiliary      // matrix      for (i = 0; i < d; i++) {          for (j = 0; j < d; j++) {               // Find the max element in the              // matrix side by side              if (c < arr[i][j]) {                  c = arr[i][j];              }               // Fill first row and              // column with 1's              if (i == 0 || j == 0) {                  dp[i][j] = 1;              }              else {                   // For every cell, check if                  // the elements at the left,                  // top and top left cells                  // from the current cell                  // are equal or not                  if (arr[i - 1][j - 1] == arr[i][j]                      && arr[i - 1][j] == arr[i][j]                      && arr[i][j - 1] == arr[i][j]) {                       // Store the minimum possible                      // submatrix size these                      // elements are part of                      dp[i][j]                          = min(dp[i - 1][j - 1],                              min(dp[i - 1][j],                                  dp[i][j - 1]))                          + 1;                  }                  else {                      // Store 1 otherwise                      dp[i][j] = 1;                  }              }          }      }       for (i = 0; i < d; i++) {          for (j = 0; j < d; j++) {               // checking maximum value              if (arr[i][j] == c) {                   // If the maximum AND                  // value occurs more                  // than once                  if (p < dp[i][j]) {                       // Update the maximum                      // size of submatrix                      p = dp[i][j];                  }              }          }      }      // final output      return p * p;  }   // Driver Program  int main()  {      vector<vector<int> > arr          = { { 9, 9, 3, 3, 4, 4 },              { 9, 9, 7, 7, 7, 4 },              { 1, 2, 7, 7, 7, 4 },              { 4, 4, 7, 7, 7, 4 },              { 5, 5, 1, 1, 2, 7 },              { 2, 7, 1, 1, 4, 4 } };       cout << MAX_value(arr) << endl;       return 0;  }  
Java
// Java program to find the length // of longest possible square  // submatrix with maximum AND  // value from the given matrix import java.util.*;  class GFG{  // Function to calculate and return // the length of square submatrix  // with maximum AND value static int MAX_value(int [][]arr) {          // Extract dimensions     int row = arr.length;     int col = arr[0].length;      // Auxiliary array     int [][]dp = new int[row][col];      // c: Stores the maximum     // value in the matrix     // p: Stores the number     // of elements in the     // submatrix having     // maximum AND value     int i = 0, j = 0;     int c = arr[0][0], p = 0;     int d = row;      // Iterate over the matrix     // to fill the auxiliary     // matrix     for(i = 0; i < d; i++)      {         for(j = 0; j < d; j++)         {                          // Find the max element in              // the matrix side by side             if (c < arr[i][j])              {                 c = arr[i][j];             }              // Fill first row and             // column with 1's             if (i == 0 || j == 0)              {                 dp[i][j] = 1;             }             else              {                  // For every cell, check if the                  // elements at the left, top and                 // top left cells from the current                 // cell are equal or not                 if (arr[i - 1][j - 1] == arr[i][j] &&                      arr[i - 1][j] == arr[i][j] &&                      arr[i][j - 1] == arr[i][j])                  {                                          // Store the minimum possible                     // submatrix size these                     // elements are part of                     dp[i][j] = Math.min(dp[i - 1][j - 1],                                Math.min(dp[i - 1][j],                                         dp[i][j - 1])) + 1;                 }                 else                 {                                          // Store 1 otherwise                     dp[i][j] = 1;                 }             }         }     }     for(i = 0; i < d; i++)     {         for(j = 0; j < d; j++)         {                          // Checking maximum value             if (arr[i][j] == c)             {                                  // If the maximum AND                 // value occurs more                 // than once                 if (p < dp[i][j])                  {                                          // Update the maximum                     // size of submatrix                     p = dp[i][j];                 }             }         }     }          // Final output     return p * p; }  // Driver code public static void main(String[] args) {     int [][]arr = { { 9, 9, 3, 3, 4, 4 },                     { 9, 9, 7, 7, 7, 4 },                     { 1, 2, 7, 7, 7, 4 },                     { 4, 4, 7, 7, 7, 4 },                     { 5, 5, 1, 1, 2, 7 },                     { 2, 7, 1, 1, 4, 4 } };      System.out.print(MAX_value(arr) + "\n"); } }  // This code contributed by amal kumar choubey 
Python3
# Python3 program to find the length # of longest possible square submatrix  # with maximum AND value from the given # matrix   # Function to calculate and return the  # length of square submatrix with  # maximum AND value  def MAX_value(arr):           # Extract dimensions      row = len(arr)      col = len(arr)       # Auxiliary array      # Initialize auxiliary array     dp = [[0 for i in range(col)]               for j in range(row)]       # c: Stores the maximum      # value in the matrix      # p: Stores the number      # of elements in the      # submatrix having      # maximum AND value      i, j = 0, 0      c, p = arr[0][0], 0     d = row      # Iterate over the matrix      # to fill the auxiliary      # matrix      for i in range(d):         for j in range(d):              # Find the max element in the              # matrix side by side              if (c < arr[i][j]):                 c = arr[i][j]              # Fill first row and              # column with 1's              if (i == 0 or j == 0):                 dp[i][j] = 1             else:                  # For every cell, check if                  # the elements at the left,                  # top and top left cells                  # from the current cell                  # are equal or not                  if (arr[i - 1][j - 1] == arr[i][j] and                      arr[i - 1][j] == arr[i][j] and                      arr[i][j - 1] == arr[i][j]):                      # Store the minimum possible                      # submatrix size these                      # elements are part of                      dp[i][j] = min(dp[i - 1][j - 1],                                 min(dp[i - 1][j],                                  dp[i][j - 1])) + 1                 else:                                          # Store 1 otherwise                      dp[i][j] = 1      for i in range(d):         for j in range(d):              # Checking maximum value              if (arr[i][j] == c):                  # If the maximum AND                  # value occurs more                  # than once                  if (p < dp[i][j]):                       # Update the maximum                      # size of submatrix                      p = dp[i][j]          # Final output      return p * p  # Driver Code  arr = [ [ 9, 9, 3, 3, 4, 4 ],          [ 9, 9, 7, 7, 7, 4 ],          [ 1, 2, 7, 7, 7, 4 ],          [ 4, 4, 7, 7, 7, 4 ],          [ 5, 5, 1, 1, 2, 7 ],          [ 2, 7, 1, 1, 4, 4 ]]   print(MAX_value(arr))  # This code is contributed by divyeshrabadiya07 
C#
// C# program to find the length // of longest possible square  // submatrix with maximum AND  // value from the given matrix using System;  class GFG{  // Function to calculate and return // the length of square submatrix  // with maximum AND value static int MAX_value(int [,]arr) {          // Extract dimensions     int row = arr.GetLength(0);     int col = arr.GetLength(1);      // Auxiliary array     int [,]dp = new int[row, col];      // c: Stores the maximum     // value in the matrix     // p: Stores the number     // of elements in the     // submatrix having     // maximum AND value     int i = 0, j = 0;     int c = arr[0, 0], p = 0;     int d = row;      // Iterate over the matrix     // to fill the auxiliary     // matrix     for(i = 0; i < d; i++)      {         for(j = 0; j < d; j++)         {                          // Find the max element in              // the matrix side by side             if (c < arr[i, j])              {                 c = arr[i, j];             }              // Fill first row and             // column with 1's             if (i == 0 || j == 0)              {                 dp[i, j] = 1;             }             else             {                                  // For every cell, check if the                  // elements at the left, top and                 // top left cells from the current                 // cell are equal or not                 if (arr[i - 1, j - 1] == arr[i, j] &&                      arr[i - 1, j] == arr[i, j] &&                      arr[i, j - 1] == arr[i, j])                  {                                          // Store the minimum possible                     // submatrix size these                     // elements are part of                     dp[i, j] = Math.Min(dp[i - 1, j - 1],                                Math.Min(dp[i - 1, j],                                         dp[i, j - 1])) + 1;                 }                 else                 {                                          // Store 1 otherwise                     dp[i, j] = 1;                 }             }         }     }     for(i = 0; i < d; i++)     {         for(j = 0; j < d; j++)         {                          // Checking maximum value             if (arr[i, j] == c)             {                                  // If the maximum AND                 // value occurs more                 // than once                 if (p < dp[i, j])                  {                                          // Update the maximum                     // size of submatrix                     p = dp[i, j];                 }             }         }     }          // Final output     return p * p; }  // Driver code public static void Main(String[] args) {     int [,]arr = { { 9, 9, 3, 3, 4, 4 },                    { 9, 9, 7, 7, 7, 4 },                    { 1, 2, 7, 7, 7, 4 },                    { 4, 4, 7, 7, 7, 4 },                    { 5, 5, 1, 1, 2, 7 },                    { 2, 7, 1, 1, 4, 4 } };      Console.Write(MAX_value(arr) + "\n"); } }  // This code is contributed by gauravrajput1 
JavaScript
<script>  // Javascript program to find the length // of longest possible square  // submatrix with maximum AND  // value from the given matrix      // Function to calculate and return     // the length of square submatrix     // with maximum AND value     function MAX_value(arr) {          // Extract dimensions         var row = arr.length;         var col = arr[0].length;          // Auxiliary array         var dp = Array(row);         for(var i = 0;i<row;i++)         dp[i] = Array(col).fill(0);          // c: Stores the maximum         // value in the matrix         // p: Stores the number         // of elements in the         // submatrix having         // maximum AND value         var i = 0, j = 0;         var c = arr[0][0], p = 0;         var d = row;          // Iterate over the matrix         // to fill the auxiliary         // matrix         for (i = 0; i < d; i++) {             for (j = 0; j < d; j++) {                  // Find the max element in                 // the matrix side by side                 if (c < arr[i][j]) {                     c = arr[i][j];                 }                  // Fill first row and                 // column with 1's                 if (i == 0 || j == 0) {                     dp[i][j] = 1;                 } else {                      // For every cell, check if the                     // elements at the left, top and                     // top left cells from the current                     // cell are equal or not                     if (arr[i - 1][j - 1] == arr[i][j] &&                      arr[i - 1][j] == arr[i][j] &&                     arr[i][j - 1] == arr[i][j]) {                          // Store the minimum possible                         // submatrix size these                         // elements are part of                         dp[i][j] = Math.min(dp[i - 1][j - 1],                          Math.min(dp[i - 1][j],                          dp[i][j - 1])) + 1;                     } else {                          // Store 1 otherwise                         dp[i][j] = 1;                     }                 }             }         }         for (i = 0; i < d; i++) {             for (j = 0; j < d; j++) {                  // Checking maximum value                 if (arr[i][j] == c) {                      // If the maximum AND                     // value occurs more                     // than once                     if (p < dp[i][j]) {                          // Update the maximum                         // size of submatrix                         p = dp[i][j];                     }                 }             }         }          // Final output         return p * p;     }      // Driver code              var arr = [ [ 9, 9, 3, 3, 4, 4 ],                     [ 9, 9, 7, 7, 7, 4 ],                     [ 1, 2, 7, 7, 7, 4 ],                      [ 4, 4, 7, 7, 7, 4 ],                     [ 5, 5, 1, 1, 2, 7 ],                      [ 2, 7, 1, 1, 4, 4 ] ];          document.write(MAX_value(arr) + "\n");  // This code contributed by umadevi9616  </script> 

Output: 
4

 

Time Complexity: O(N*N), as we are using nested loops to traverse N*N times.

Auxiliary Space: O(N*N), as we are using extra space for matrix.


Next Article
Submatrix of given size with maximum 1's

V

vabzcode12
Improve
Article Tags :
  • Dynamic Programming
  • Combinatorial
  • Matrix
  • Competitive Programming
  • DSA
  • Bitwise-AND
Practice Tags :
  • Combinatorial
  • Dynamic Programming
  • Matrix

Similar Reads

  • Submatrix of given size with maximum 1's
    Given a binary matrix mat[][] and an integer K, the task is to find the submatrix of size K*K such that it contains maximum number of 1's in the matrix. Examples: Input: mat[][] = {{1, 0, 1}, {1, 1, 0}, {1, 0, 0}}, K = 2 Output: 3 Explanation: In the given matrix, there are 4 sub-matrix of order 2*2
    15+ min read
  • Maximum size square sub-matrix with all 1s
    Given a binary matrix mat of size n * m, the task is to find out the maximum length of a side of a square sub-matrix with all 1s. Example: Input: mat = [ [0, 1, 1, 0, 1], [1, 1, 0, 1, 0], [0, 1, 1, 1, 0], [1, 1, 1, 1, 0], [1, 1, 1, 1, 1], [0, 0, 0, 0, 0] ] Output: 3Explanation: The maximum length of
    15+ min read
  • Maximum size square Sub-Matrix with sum less than or equals to K
    Given a Matrix arr[][] of size M x N having positive integers and a number K, the task is to find the size of the largest square sub-matrix whose sum of elements is less than or equals to K. Example: Input: arr[][] = { { 1, 1, 3, 2, 4, 3, 2 }, { 1, 1, 3, 2, 4, 3, 2 }, { 1, 1, 3, 2, 4, 3, 2 } }, K =
    12 min read
  • Count of square submatrices with average at least K
    Given a matrix arr[][] of size NxM and an integer K, the task is to find the count of square submatrices in the given matrix with the average of elements greater than or equal to K. Examples: Input: K = 4, arr[][] = {{2, 2, 3}, {3, 4, 5}, {4, 5, 5}}Output: 7Explanation: The following square submatri
    12 min read
  • Longest Sub-array with maximum average value
    Given an array arr[] of n integers. The task is to find the maximum length of the sub-array which has the maximum average value (average of the elements of the sub-array). [Tex] [/Tex]Examples: Input: arr[] = {2, 3, 4, 5, 6} Output: 1 {6} is the required sub-arrayInput: arr[] = {6, 1, 6, 6, 0} Outpu
    6 min read
  • Maximum sum square sub-matrix of given size
    Given a 2d array mat[][] of order n * n, and an integer k. Your task is to find a submatrix of order k * k, such that sum of all the elements in the submatrix is maximum possible. Note: Matrix mat[][] contains zero, positive and negative integers. Examples: Input: k = 3mat[][] = [ [ 1, 2, -1, 4 ] [
    15+ min read
  • Smallest submatrix with Kth maximum XOR
    Given a matrix m[][] of dimensions N × M and an integer K, calculate XOR(i, j) which is equal to the Bitwise Xor of all elements of submatrix from indices (1, 1) to (i, j)), for every index of the matrix. The task is to find the submatrix {(1, 1), ..., (i, j)} having Kth maximum XOR(i, j) value. If
    9 min read
  • Largest Submatrix With Sum 0
    Given a 2D matrix of dimension n x m, the task is to find the area of largest submatrix whose sum is 0. Examples: Input: mat[][] = [[9, 7, 16, 5], [1, -6, -7, 3], [1, 8, 7, 9], [7, -2, 0, 10]]Output: 6Explanation: Input: mat[][] = [[1, 2, 3], [-3, -2, -1], [1, 7, 5]]Output: 6Explanation: Input: mat[
    8 min read
  • Maximum Subarray Sum possible by replacing an Array element by its Square
    Given an array a[] consisting of N integers, the task is to find the maximum subarray sum that can be obtained by replacing a single array element by its square. Examples: Input: a[] = {1, -5, 8, 12, -8} Output: 152 Explanation: Replacing 12 by 144, the subarray {8, 144} generates the maximum possib
    12 min read
  • Largest square sub-matrix with equal row, column, and diagonal sum
    Given a matrix mat[][] of dimensions N*M, the task is to find the size of the largest square submatrix such that the sum of all rows, columns, diagonals in that submatrix are equal. Examples: Input: N = 3, M = 4, mat[][] = [[5, 1, 3, 1], [9, 3, 3, 1], [1, 3, 3, 8]]Output: 2Explanation:The submatrix
    11 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