The Wayback Machine - https://web.archive.org/web/20241009215425/https://www.geeksforgeeks.org/maximum-size-rectangle-binary-sub-matrix-1s/
Open In App

Maximum size rectangle binary sub-matrix with all 1s

Last Updated : 08 Aug, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Given a binary matrix, find the maximum size rectangle binary-sub-matrix with all 1’s. 

Example: 

Input:
0 1 1 0
1 1 1 1
1 1 1 1
1 1 0 0
Output :
8
Explanation :
The largest rectangle with only 1's is from
(1, 0) to (2, 3) which is
1 1 1 1
1 1 1 1

Input:
0 1 1
1 1 1
0 1 1
Output:
6
Explanation :
The largest rectangle with only 1's is from
(0, 1) to (2, 2) which is
1 1
1 1
1 1

There is already an algorithm discussed a dynamic programming based solution for finding the largest square with 1s. 

Approach: 

In this post, an interesting method is discussed that uses largest rectangle under histogram as a subroutine. 

If the height of bars of the histogram is given then the largest area of the histogram can be found. This way in each row, the largest area of bars of the histogram can be found. To get the largest rectangle full of 1’s, update the next row with the previous row and find the largest area under the histogram, i.e. consider each 1’s as filled squares and 0’s with an empty square and consider each row as the base.

Illustration: 

Input :
0 1 1 0
1 1 1 1
1 1 1 1
1 1 0 0
Step 1:
0 1 1 0 maximum area = 2
Step 2:
row 1 1 2 2 1 area = 4, maximum area becomes 4
row 2 2 3 3 2 area = 8, maximum area becomes 8
row 3 3 4 0 0 area = 6, maximum area remains 8

Algorithm: 

  1. Run a loop to traverse through the rows.
  2. Now If the current row is not the first row then update the row as follows, if matrix[i][j] is not zero then matrix[i][j] = matrix[i-1][j] + matrix[i][j].
  3. Find the maximum rectangular area under the histogram, consider the ith row as heights of bars of a histogram. This can be calculated as given in this article Largest Rectangular Area in a Histogram
  4. Do the previous two steps for all rows and print the maximum area of all the rows.

Note: It is strongly recommended to refer to this post first as most of the code is taken from there. 

Implementation 

C++
// C++ program to find largest
// rectangle with all 1s
// in a binary matrix
#include <bits/stdc++.h>
using namespace std;

// Rows and columns in input matrix
#define R 4
#define C 4

// Finds the maximum area under 
// the histogram represented
// by histogram.  See below article for details.


int maxHist(int row[])
{
    // Create an empty stack. 
    // The stack holds indexes of
    // hist[] array/ The bars stored 
    // in stack are always
    // in increasing order of their heights.
    stack<int> result;

    int top_val; // Top of stack

    int max_area = 0; // Initialize max area in current
    // row (or histogram)

    int area = 0; // Initialize area with current top

    // Run through all bars of given histogram (or row)
    int i = 0;
    while (i < C) {
        // If this bar is higher than the bar on top stack,
        // push it to stack
        if (result.empty() || row[result.top()] <= row[i])
            result.push(i++);

        else {
            // If this bar is lower than top of stack, then
            // calculate area of rectangle with stack top as
            // the smallest (or minimum height) bar. 'i' is
            // 'right index' for the top and element before
            // top in stack is 'left index'
            top_val = row[result.top()];
            result.pop();
            area = top_val * i;

            if (!result.empty())
                area = top_val * (i - result.top() - 1);
            max_area = max(area, max_area);
        }
    }

    // Now pop the remaining bars from stack and calculate
    // area with every popped bar as the smallest bar
    while (!result.empty()) {
        top_val = row[result.top()];
        result.pop();
        area = top_val * i;
        if (!result.empty())
            area = top_val * (i - result.top() - 1);

        max_area = max(area, max_area);
    }
    return max_area;
}

// Returns area of the largest rectangle with all 1s in
// A[][]
int maxRectangle(int A[][C])
{
    // Calculate area for first row and initialize it as
    // result
    int result = maxHist(A[0]);

    // iterate over row to find maximum rectangular area
    // considering each row as histogram
    for (int i = 1; i < R; i++) {

        for (int j = 0; j < C; j++)

            // if A[i][j] is 1 then add A[i -1][j]
            if (A[i][j])
                A[i][j] += A[i - 1][j];

        // Update result if area with current row (as last
        // row) of rectangle) is more
        result = max(result, maxHist(A[i]));
    }

    return result;
}

// Driver code
int main()
{
    int A[][C] = {
        { 0, 1, 1, 0 },
        { 1, 1, 1, 1 },
        { 1, 1, 1, 1 },
        { 1, 1, 0, 0 },
    };

    cout << "Area of maximum rectangle is "
         << maxRectangle(A);

    return 0;
}
Java
// Java program to find largest rectangle with all 1s
// in a binary matrix
import java.io.*;
import java.util.*;

class GFG {
    // Finds the maximum area under the histogram
    // represented by histogram.  See below article for

    static int maxHist(int R, int C, int row[])
    {
        // Create an empty stack. The stack holds indexes of
        // hist[] array/ The bars stored in stack are always
        // in increasing order of their heights.
        Stack<Integer> result = new Stack<Integer>();

        int top_val; // Top of stack

        int max_area = 0; // Initialize max area in current
        // row (or histogram)

        int area = 0; // Initialize area with current top

        // Run through all bars of given histogram (or row)
        int i = 0;
        while (i < C) {
            // If this bar is higher than the bar on top
            // stack, push it to stack
            if (result.empty()
                || row[result.peek()] <= row[i])
                result.push(i++);

            else {
                // If this bar is lower than top of stack,
                // then calculate area of rectangle with
                // stack top as the smallest (or minimum
                // height) bar. 'i' is 'right index' for the
                // top and element before top in stack is
                // 'left index'
                top_val = row[result.peek()];
                result.pop();
                area = top_val * i;

                if (!result.empty())
                    area
                        = top_val * (i - result.peek() - 1);
                max_area = Math.max(area, max_area);
            }
        }

        // Now pop the remaining bars from stack and
        // calculate area with every popped bar as the
        // smallest bar
        while (!result.empty()) {
            top_val = row[result.peek()];
            result.pop();
            area = top_val * i;
            if (!result.empty())
                area = top_val * (i - result.peek() - 1);

            max_area = Math.max(area, max_area);
        }
        return max_area;
    }

    // Returns area of the largest rectangle with all 1s in
    // A[][]
    static int maxRectangle(int R, int C, int A[][])
    {
        // Calculate area for first row and initialize it as
        // result
        int result = maxHist(R, C, A[0]);

        // iterate over row to find maximum rectangular area
        // considering each row as histogram
        for (int i = 1; i < R; i++) {

            for (int j = 0; j < C; j++)

                // if A[i][j] is 1 then add A[i -1][j]
                if (A[i][j] == 1)
                    A[i][j] += A[i - 1][j];

            // Update result if area with current row (as
            // last row of rectangle) is more
            result = Math.max(result, maxHist(R, C, A[i]));
        }

        return result;
    }

    // Driver code
    public static void main(String[] args)
    {
        int R = 4;
        int C = 4;

        int A[][] = {
            { 0, 1, 1, 0 },
            { 1, 1, 1, 1 },
            { 1, 1, 1, 1 },
            { 1, 1, 0, 0 },
        };
        System.out.print("Area of maximum rectangle is "
                         + maxRectangle(R, C, A));
    }
}

// Contributed by Prakriti Gupta
Python
# Python3 program to find largest rectangle
# with all 1s in a binary matrix

# Finds the maximum area under the
# histogram represented
# by histogram. See below article for details.


class Solution():
    def maxHist(self, row):
        # Create an empty stack. The stack holds
        # indexes of hist array / The bars stored
        # in stack are always in increasing order
        # of their heights.
        result = []

        # Top of stack
        top_val = 0

        # Initialize max area in current
        max_area = 0
        # row (or histogram)

        area = 0  # Initialize area with current top

        # Run through all bars of given
        # histogram (or row)
        i = 0
        while (i < len(row)):

            # If this bar is higher than the
            # bar on top stack, push it to stack
            if (len(result) == 0) or (row[result[-1]] <= row[i]):
                result.append(i)
                i += 1
            else:

                # If this bar is lower than top of stack,
                # then calculate area of rectangle with
                # stack top as the smallest (or minimum
                # height) bar. 'i' is 'right index' for
                # the top and element before top in stack
                # is 'left index'
                top_val = row[result.pop()]
                area = top_val * i

                if (len(result)):
                    area = top_val * (i - result[-1] - 1)
                max_area = max(area, max_area)

        # Now pop the remaining bars from stack
        # and calculate area with every popped
        # bar as the smallest bar
        while (len(result)):
            top_val = row[result.pop()]
            area = top_val * i
            if (len(result)):
                area = top_val * (i - result[-1] - 1)

            max_area = max(area, max_area)

        return max_area

    # Returns area of the largest rectangle
    # with all 1s in A
    def maxRectangle(self, A):

        # Calculate area for first row and
        # initialize it as result
        result = self.maxHist(A[0])

        # iterate over row to find maximum rectangular
        # area considering each row as histogram
        for i in range(1, len(A)):

            for j in range(len(A[i])):

                # if A[i][j] is 1 then add A[i -1][j]
                if (A[i][j]):
                    A[i][j] += A[i - 1][j]

            # Update result if area with current
            # row (as last row) of rectangle) is more
            result = max(result, self.maxHist(A[i]))

        return result


# Driver Code
if __name__ == '__main__':
    A = [[0, 1, 1, 0],
         [1, 1, 1, 1],
         [1, 1, 1, 1],
         [1, 1, 0, 0]]
    ans = Solution()

    print("Area of maximum rectangle is",
          ans.maxRectangle(A))

# This code is contributed
# by Aaryaman Sharma
C#
// C# program to find largest rectangle
// with all 1s in a binary matrix
using System;
using System.Collections.Generic;

class GFG {
    // Finds the maximum area under the
    // histogram represented by histogram.
    public static int maxHist(int R, int C, int[] row)
    {
        // Create an empty stack. The stack
        // holds indexes of hist[] array.
        // The bars stored in stack are always
        // in increasing order of their heights.
        Stack<int> result = new Stack<int>();

        int top_val; // Top of stack

        int max_area = 0; // Initialize max area in
        // current row (or histogram)

        int area = 0; // Initialize area with
        // current top

        // Run through all bars of
        // given histogram (or row)
        int i = 0;
        while (i < C) {
            // If this bar is higher than the
            // bar on top stack, push it to stack
            if (result.Count == 0
                || row[result.Peek()] <= row[i]) {
                result.Push(i++);
            }

            else {
                // If this bar is lower than top
                // of stack, then calculate area of
                // rectangle with stack top as
                // the smallest (or minimum height)
                // bar. 'i' is 'right index' for
                // the top and element before
                // top in stack is 'left index'
                top_val = row[result.Peek()];
                result.Pop();
                area = top_val * i;

                if (result.Count > 0) {
                    area
                        = top_val * (i - result.Peek() - 1);
                }
                max_area = Math.Max(area, max_area);
            }
        }

        // Now pop the remaining bars from
        // stack and calculate area with
        // every popped bar as the smallest bar
        while (result.Count > 0) {
            top_val = row[result.Peek()];
            result.Pop();
            area = top_val * i;
            if (result.Count > 0) {
                area = top_val * (i - result.Peek() - 1);
            }

            max_area = Math.Max(area, max_area);
        }
        return max_area;
    }

    // Returns area of the largest
    // rectangle with all 1s in A[][]
    public static int maxRectangle(int R, int C, int[][] A)
    {
        // Calculate area for first row
        // and initialize it as result
        int result = maxHist(R, C, A[0]);

        // iterate over row to find
        // maximum rectangular area
        // considering each row as histogram
        for (int i = 1; i < R; i++) {
            for (int j = 0; j < C; j++) {

                // if A[i][j] is 1 then
                // add A[i -1][j]
                if (A[i][j] == 1) {
                    A[i][j] += A[i - 1][j];
                }
            }

            // Update result if area with current
            // row (as last row of rectangle) is more
            result = Math.Max(result, maxHist(R, C, A[i]));
        }

        return result;
    }

    // Driver code
    public static void Main(string[] args)
    {
        int R = 4;
        int C = 4;

        int[][] A
            = new int[][] { new int[] { 0, 1, 1, 0 },
                            new int[] { 1, 1, 1, 1 },
                            new int[] { 1, 1, 1, 1 },
                            new int[] { 1, 1, 0, 0 } };
        Console.Write("Area of maximum rectangle is "
                      + maxRectangle(R, C, A));
    }
}

// This code is contributed by Shrikant13
JavaScript
<script>
    // Javascript program to find largest rectangle
    // with all 1s in a binary matrix
    
    // Finds the maximum area under the
    // histogram represented by histogram.
    function maxHist(R, C, row)
    {
        // Create an empty stack. The stack
        // holds indexes of hist[] array.
        // The bars stored in stack are always
        // in increasing order of their heights.
        let result = [];
 
        let top_val; // Top of stack
 
        let max_area = 0; // Initialize max area in
        // current row (or histogram)
 
        let area = 0; // Initialize area with
        // current top
 
        // Run through all bars of
        // given histogram (or row)
        let i = 0;
        while (i < C) {
            // If this bar is higher than the
            // bar on top stack, push it to stack
            if (result.length == 0
                || row[result[result.length - 1]] <= row[i]) {
                result.push(i++);
            }
 
            else {
                // If this bar is lower than top
                // of stack, then calculate area of
                // rectangle with stack top as
                // the smallest (or minimum height)
                // bar. 'i' is 'right index' for
                // the top and element before
                // top in stack is 'left index'
                top_val = row[result[result.length - 1]];
                result.pop();
                area = top_val * i;
 
                if (result.length > 0) {
                    area = top_val * (i - result[result.length - 1] - 1);
                }
                max_area = Math.max(area, max_area);
            }
        }
 
        // Now pop the remaining bars from
        // stack and calculate area with
        // every popped bar as the smallest bar
        while (result.length > 0) {
            top_val = row[result[result.length - 1]];
            result.pop();
            area = top_val * i;
            if (result.length > 0) {
                area = top_val * (i - result[result.length - 1] - 1);
            }
 
            max_area = Math.max(area, max_area);
        }
        return max_area;
    }
 
    // Returns area of the largest
    // rectangle with all 1s in A[][]
    function maxRectangle(R, C, A)
    {
        // Calculate area for first row
        // and initialize it as result
        let result = maxHist(R, C, A[0]);
 
        // iterate over row to find
        // maximum rectangular area
        // considering each row as histogram
        for (let i = 1; i < R; i++) {
            for (let j = 0; j < C; j++) {
 
                // if A[i][j] is 1 then
                // add A[i -1][j]
                if (A[i][j] == 1) {
                    A[i][j] += A[i - 1][j];
                }
            }
 
            // Update result if area with current
            // row (as last row of rectangle) is more
            result = Math.max(result, maxHist(R, C, A[i]));
        }
 
        return result;
    }
    
    let R = 4;
    let C = 4;

      let A = [ [ 0, 1, 1, 0 ],
               [ 1, 1, 1, 1 ],
               [ 1, 1, 1, 1 ],
               [ 1, 1, 0, 0 ] ];
    document.write("Area of maximum rectangle is "
                  + maxRectangle(R, C, A));
    
    // This code is contributed by decode2207.
</script>

Output
Area of maximum rectangle is 8

Complexity Analysis:  

  • Time Complexity: O(R x C x C). 
    One traversal of the matrix is required, another is traversal of every column, so the time complexity is O(R X C X C)
  • Auxiliary Space: O(C). 
    Stack is required to store the columns, so space complexity is O(C)

Approach : Dynamic Programming

For each cell, use dynamic programming to get the maximum height of the rectangle that ends 
at the cell. To get the maximum width of the rectangle with the cell as its bottom-right corner,
expand leftwards. To calculate the maximum area for each cell, expand leftward.
Keep track of the maximum

Follow the given steps to solve the problem :

  • Create two auxiliary matrices.
  • One to store the maximum height of consecutive 1s above a cell
  • One to store the maximum height of consecutive 1s below a cell
  • For each cell in the matrix calculate the maximum area by considering the heights stored in the auxiliary matrices
  • Keep track of the maximum area found

Below is the implementation of the above approach:

C++
#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

int maximalRectangle(vector<vector<char>>& matrix) {
    if (matrix.empty() || matrix[0].empty()) {
        return 0;
    }

    int m = matrix.size();
    int n = matrix[0].size();
    vector<int> left(n, 0);
    vector<int> right(n, n);
    vector<int> height(n, 0);
    int maxArea = 0;

    for (const auto& row : matrix) {
        int curLeft = 0, curRight = n;

        // Update height array
        for (int j = 0; j < n; j++) {
            if (row[j] == '1') {
                height[j]++;
            } else {
                height[j] = 0;
            }
        }

        // Update left boundary array
        for (int j = 0; j < n; j++) {
            if (row[j] == '1') {
                left[j] = max(left[j], curLeft);
            } else {
                left[j] = 0;
                curLeft = j + 1;
            }
        }

        // Update right boundary array
        for (int j = n - 1; j >= 0; j--) {
            if (row[j] == '1') {
                right[j] = min(right[j], curRight);
            } else {
                right[j] = n;
                curRight = j;
            }
        }

        // Calculate maximum area for each cell
        for (int j = 0; j < n; j++) {
            maxArea = max(maxArea, (right[j] - left[j]) * height[j]);
        }
    }

    return maxArea;
}

int main() {
    vector<vector<char>> matrix1 = {
        {'0', '1', '1', '0'},
        {'1', '1', '1', '1'},
        {'1', '1', '1', '1'},
        {'1', '1', '0', '0'}
    };

    cout << maximalRectangle(matrix1) << endl;

    return 0;
}


//This code is contributed by ayush panwar
Java
// Java Code
import java.io.*;
import java.util.Arrays;

public class GFG{
    
    public static int maximalRectangle(char[][] matrix) {
        if (matrix == null || matrix.length == 0) {
            return 0;
        }
        
        int m = matrix.length;
        int n = matrix[0].length;
        int[] left = new int[n];   // Array to store the left boundary of consecutive 1's
        int[] right = new int[n];  // Array to store the right boundary of consecutive 1's
        int[] height = new int[n]; // Array to store the height of consecutive 1's
        
        Arrays.fill(right, n);
        int maxArea = 0;
        
        for (char[] row : matrix) {
            int curLeft = 0, curRight = n;
            
            // Update height array
            for (int j = 0; j < n; j++) {
                if (row[j] == '1') {
                    height[j]++;
                } else {
                    height[j] = 0;
                }
            }
            
            // Update left boundary array
            for (int j = 0; j < n; j++) {
                if (row[j] == '1') {
                    left[j] = Math.max(left[j], curLeft);
                } else {
                    left[j] = 0;
                    curLeft = j + 1;
                }
            }
            
            // Update right boundary array
            for (int j = n - 1; j >= 0; j--) {
                if (row[j] == '1') {
                    right[j] = Math.min(right[j], curRight);
                } else {
                    right[j] = n;
                    curRight = j;
                }
            }
            
            // Calculate maximum area for each cell
            for (int j = 0; j < n; j++) {
                maxArea = Math.max(maxArea, (right[j] - left[j]) * height[j]);
            }
        }
        
        return maxArea;
    }

    public static void main(String[] args) {
        char[][] matrix1 = {
            {'0', '1', '1', '0'},
            {'1', '1', '1', '1'},
            {'1', '1', '1', '1'},
            {'1', '1', '0', '0'}
        };
        
        System.out.println(maximalRectangle(matrix1));
    }
}

// This code is contributed by guptapratik
Python
def maximalRectangle(matrix):
    if not matrix:
        return 0

    m, n = len(matrix), len(matrix[0])
    left = [0] * n  # Array to store the left boundary of consecutive 1's
    right = [n] * n  # Array to store the right boundary of consecutive 1's
    height = [0] * n  # Array to store the height of consecutive 1's

    max_area = 0

    for i in range(m):
        cur_left, cur_right = 0, n

        # Update height array
        for j in range(n):
            if matrix[i][j] == '1':
                height[j] += 1
            else:
                height[j] = 0

        # Update left boundary array
        for j in range(n):
            if matrix[i][j] == '1':
                left[j] = max(left[j], cur_left)
            else:
                left[j] = 0
                cur_left = j + 1

        # Update right boundary array
        for j in range(n-1, -1, -1):
            if matrix[i][j] == '1':
                right[j] = min(right[j], cur_right)
            else:
                right[j] = n
                cur_right = j

        # Calculate maximum area for each cell
        for j in range(n):
            max_area = max(max_area, (right[j] - left[j]) * height[j])

    return max_area


matrix1 = [
    ["0", "1", "1", "0"],
    ["1", "1", "1", "1"],
    ["1", "1", "1", "1"],
    ["1", "1", "0", "0"]
]
print(maximalRectangle(matrix1))
JavaScript
function maximalRectangle(matrix) {
    if (!matrix || matrix.length === 0) {
        return 0;
    }
    
    const m = matrix.length;
    const n = matrix[0].length;
    const left = new Array(n).fill(0);   // Array to store the left boundary of consecutive 1's
    const right = new Array(n).fill(n);  // Array to store the right boundary of consecutive 1's
    const height = new Array(n).fill(0); // Array to store the height of consecutive 1's
    
    let maxArea = 0;
    
    for (const row of matrix) {
        let curLeft = 0, curRight = n;
        
        // Update height array
        for (let j = 0; j < n; j++) {
            if (row[j] === '1') {
                height[j]++;
            } else {
                height[j] = 0;
            }
        }
        
        // Update left boundary array
        for (let j = 0; j < n; j++) {
            if (row[j] === '1') {
                left[j] = Math.max(left[j], curLeft);
            } else {
                left[j] = 0;
                curLeft = j + 1;
            }
        }
        
        // Update right boundary array
        for (let j = n - 1; j >= 0; j--) {
            if (row[j] === '1') {
                right[j] = Math.min(right[j], curRight);
            } else {
                right[j] = n;
                curRight = j;
            }
        }
        
        // Calculate maximum area for each cell
        for (let j = 0; j < n; j++) {
            maxArea = Math.max(maxArea, (right[j] - left[j]) * height[j]);
        }
    }
    
    return maxArea;
}

const matrix1 = [
    ['0', '1', '1', '0'],
    ['1', '1', '1', '1'],
    ['1', '1', '1', '1'],
    ['1', '1', '0', '0']
];

console.log(maximalRectangle(matrix1));

Output
8

Time Complexity: O(m * n), where m is the number of rows & n is the number of columns in the input matrix.

Auxiliary Complexity: O(n)



Previous Article
Next Article

Similar Reads

Maximum size rectangle binary sub-matrix with all 1s | Set 2
Given a binary matrix mat[][] of size N*M, find the maximum size rectangle binary-sub-matrix with all 1’s. Examples: Input: mat[][] = { {0, 1, 1, 0}, {1, 1, 1, 1}, {1, 1, 1, 1}, {1, 1, 0, 0} }Output: 8Explanation: The largest rectangle formed with only 1s is either: (0, 1) to (2, 2) or (1, 1) to (2, 3) which is1 1 1 11 1 1 1 Input: mat[][] = { {0,
15+ min read
Maximum area of a Rectangle that can be circumscribed about a given Rectangle of size LxW
Given a rectangle of dimensions L and W. The task is to find the maximum area of a rectangle that can be circumscribed about a given rectangle with dimensions L and W. Examples: Input: L = 10, W = 10Output: 200 Input: L = 18, W = 12Output: 450 Approach: Let below is the given rectangle EFGH of dimensions L and W. We have to find the area of rectang
4 min read
Count ways to reach target cell in a rectangle with restricted sub-rectangle
Given a grid of size M x N and two integers X and Y. A restricted area is defined as the lower left sub-rectangle consisting of X x Y blocks. Starting from the upper left cell find the number of ways to reach the bottom right cell where a legal move is defined to move right or down but never into the restricted area or outside the given grid.  Note
13 min read
Check whether row or column swaps produce maximum size binary sub-matrix with all 1s
Given a binary matrix, the task is to find whether row swaps or column swaps give maximum size sub-matrix with all 1's. In a row swap, we are allowed to swap any two rows. In a column swap, we are allowed to swap any two columns. Output "Row Swap" or "Column Swap" and the maximum size. Examples: Input : 1 1 1 1 0 1 Output : Column Swap 4 By swappin
13 min read
Count the number of sub-arrays such that the average of elements present in the sub-array is greater than that not present in the sub-array
Given an array of integers arr[], the task is to count the number of sub-arrays such that the average of elements present in the sub-array is greater than the average of elements that are not present in the sub-array.Examples: Input: arr[] = {6, 3, 5} Output: 3 The sub-arrays are {6}, {5} and {6, 3, 5} because their averages are greater than {3, 5}
8 min read
Maximum size square sub-matrix with all 1s
Given a binary matrix, find out the maximum size square sub-matrix with all 1s. For example, consider the below binary matrix. Recommended PracticeLargest square formed in a matrixTry It! Algorithm: Let the given binary matrix be M[R][C]. The idea of the algorithm is to construct an auxiliary size matrix S[][] in which each entry S[i][j] represents
15+ min read
Find the number of rectangles of size 2*1 which can be placed inside a rectangle of size n*m
Given two integers n, m. Find the number of rectangles of size 2*1 that can be placed inside a rectangle of size n*m. Note: No two small rectangles overlap.Each small rectangle lies entirely inside the large rectangle. It is allowed to touch the edges of the large rectangle. Examples: Input : n = 3, m =3 Output : 4 Input : n = 2, m = 4 Output : 4 A
6 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 = 4 Output: 2 Explanation: Maximum size square Sub-M
12 min read
Print maximum sum square sub-matrix of given size
Given an N x N matrix, find a k x k submatrix where k <= N and k >= 1, such that sum of all the elements in submatrix is maximum. The input matrix can contain zero, positive and negative numbers. For example consider below matrix, if k = 3, then output should print the sub-matrix enclosed in blue. We strongly recommend you to minimize your br
15+ min read
Ratio of area of a rectangle with the rectangle inscribed in it
Given two rectangles, X with a ratio of length to width a:b and Y with a ratio of length to width c:d respectively. Both the rectangles can be resized as long as the ratio of sides remains the same. The task is to place the second rectangle inside the first rectangle such that at least 1 side is equal and that side overlaps of both the rectangles a
7 min read
Largest subset of rectangles such that no rectangle fit in any other rectangle
Given height and width of N rectangles. The task is to find the size of the largest subset such that no pair of rectangles fit within each other. Note that if H1 ? H2 and W1 ? W2 then rectangle 1 fits inside rectangle 2. Examples: Input: arr[] = {{1, 3}, {2, 2}, {1, 3}} Output: 2 The required sub-set is {{1, 3}, {2, 2}} {1, 3} is included only once
15 min read
Given an n x n square matrix, find sum of all sub-squares of size k x k
Given an n x n square matrix, find sum of all sub-squares of size k x k where k is smaller than or equal to n. Examples : Input: n = 5, k = 3 arr[][] = { {1, 1, 1, 1, 1}, {2, 2, 2, 2, 2}, {3, 3, 3, 3, 3}, {4, 4, 4, 4, 4}, {5, 5, 5, 5, 5}, }; Output: 18 18 18 27 27 27 36 36 36 Input: n = 3, k = 2 arr[][] = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9}, }; Outpu
15+ min read
Find all unique pairs of maximum and second maximum elements over all sub-arrays in O(NlogN)
Let [Tex](a, b) [/Tex]represent the ordered pair of the second maximum and the maximum element of an array respectively. We need to find all such unique pairs overall contiguous sub-arrays of a given array. Examples: Input: Arr = [ 1, 2, 3, 4, 5 ] Output: (1, 2) (2, 3) (3, 4) (4, 5) Input: Arr = [ 1, 1, 2 ] Output: (1, 1) (1, 2) Input: Arr = [ 1, 2
13 min read
Ways to divide a binary array into sub-arrays such that each sub-array contains exactly one 1
Give an integer array arr[] consisting of elements from the set {0, 1}. The task is to print the number of ways the array can be divided into sub-arrays such that each sub-array contains exactly one 1. Examples: Input: arr[] = {1, 0, 1, 0, 1} Output: 4 Below are the possible ways: {1, 0}, {1, 0}, {1}{1}, {0, 1, 0}, {1}{1, 0}, {1}, {0, 1}{1}, {0, 1}
6 min read
Maximum sub-array sum after dividing array into sub-arrays based on the given queries
Given an array arr[] and an integer k, we can cut this array at k different positions where k[] stores the positions of all the cuts required. The task is to print maximum sum among all the cuts after every cut made. Every cut is of the form of an integer x where x denotes a cut between arr[x] and arr[x + 1]. Examples: Input: arr[] = {4, 5, 6, 7, 8
9 min read
Find the maximum element in the array other than Ai
Given an array arr[] of size N. The task is to find maximum element among N - 1 elements other than arr[i] for each i from 1 to N.Examples: Input: arr[] = {2, 5, 6, 1, 3} Output: 6 6 5 6 6 Input: arr[] = {1, 2, 3} Output: 3 3 2 Approach: An efficient approach is to make prefix and suffix array of maximum elements and find maximum element among N -
6 min read
Given a string and an integer k, find the kth sub-string when all the sub-strings are sorted according to the given condition
Given a string str, its sub-strings are formed in such a way that all the sub-strings starting with the first character of the string will occur first in the sorted order of their lengths followed by all the sub-strings starting with the second character of the string in the sorted order of their lengths and so on. For example for the string abc, i
9 min read
Finding the maximum square sub-matrix with all equal elements
Given a N x N matrix, determine the maximum K such that K x K is a submatrix with all equal elements i.e., all the elements in this submatrix must be same. Constraints: 1 <= N <= 1000 0 <= Ai , j <= 109 Examples: Input : a[][] = {{2, 3, 3}, {2, 3, 3}, {2, 2, 2}} Output : 2 Explanation: A 2x2 matrix is formed from index A0,1 to A1,2 Inpu
10 min read
Find if there is a rectangle in binary matrix with corners as 1
There is a given binary matrix, we need to find if there exists any rectangle or square in the given matrix whose all four corners are equal to Examples: Input : mat[][] = { 1 0 0 1 0 0 0 1 0 1 0 0 0 1 0 1 0 1 0 1} Output : Yes as there exists- 1 0 1 0 1 0 1 0 1Recommended PracticeFind rectangle with corners as 1Try It! Brute Force Approach: We sta
15+ min read
Maximum sum not exceeding K possible for any rectangle of a Matrix
Given a matrix mat[][] of dimensions N * M, and an integer K, the task is to find the maximum sum of any rectangle possible from the given matrix, whose sum of elements is at most K. Examples: Input: mat[][] ={{1, 0, 1}, {0, -2, 3}}, K = 2Output: 2Explanation: The maximum sum possible in any rectangle from the matrix is 2 (<= K), obtained from t
11 min read
Maximum sum rectangle in a 2D matrix | DP-27
Given a 2D array, find the maximum sum submatrix in it. For example, in the following 2D array, the maximum sum submatrix is highlighted with blue rectangle and sum of all elements in this submatrix is 29. This problem is mainly an extension of Largest Sum Contiguous Subarray for 1D array.   Recommended PracticeMaximum sum RectangleTry It!The Naive
15+ min read
Maximum size of square such that all submatrices of that size have sum less than K
Given an N x M matrix of integers and an integer K, the task is to find the size of the maximum square sub-matrix (S x S), such that all square sub-matrices of the given matrix of that size have a sum less than K. Examples: Input: K = 30 mat[N][M] = {{1, 2, 3, 4, 6}, {5, 3, 8, 1, 2}, {4, 6, 7, 5, 5}, {2, 4, 8, 9, 4} }; Output: 2 Explanation: All Su
15+ min read
Maximum subarray size, such that all subarrays of that size have sum less than k
Given an array of n positive integers and a positive integer k, the task is to find the maximum subarray size such that all subarrays of that size have the sum of elements less than or equals to k. Examples : Input : arr[] = {1, 2, 3, 4} and k = 8. Output : 2 Sum of subarrays of size 1: 1, 2, 3, 4. Sum of subarrays of size 2: 3, 5, 7. Sum of subarr
15+ min read
Queries on number of Binary sub-matrices of Given size
Given a Binary Matrix of size N X M, the task is to answer Q queries of the following type; Query(a, b): Find the number of sub matrices of size a X a with each of its element consisting of the Binary Number b. We basically need to find submatrices of given sizes with all 1s or all 0s. Examples: Input : N = 5, M = 4 m[][] = { { 0, 0, 1, 1 }, { 0, 0
12 min read
Maximum product quadruple (sub-sequence of size 4) in array
Given an integer array, find a maximum product of a quadruple in the array. Examples: Input: [10, 3, 5, 6, 20] Output: 6000 Multiplication of 10, 5, 6 and 20 Input: [-10, -3, -5, -6, -20] Output: 6000 Input: [1, -4, 3, -6, 7, 0] Output: 504 Approach 1 (Naive, O([Tex] [/Tex]) time, O(1) Space) Steps to solve this problem: 1.check if n is smaller tha
15+ min read
Maximum number of Unique integers in Sub-Array of given size
Given an array of N integers and a number M. The task is to find out the maximum number of unique integers among all possible contiguous subarrays of size M. Examples: Input : arr[] = {5, 3, 5, 2, 3, 2}, M = 3 Output : 3 Explanation: In the sample test case, there are 4 subarrays of size 3. s1 = (5, 3, 5)- Has 2 unique numbers. s2 = (3, 5, 2)- Has
12 min read
Maximum size of sub-array that satisfies the given condition
Given an array arr[] of integers. The task is to return the length of the maximum size sub-array such that either one of the condition is satisfied: arr[k] > arr[k + 1] when k is odd and arr[k] < arr[k + 1] when k is even.arr[k] > arr[k + 1] when k is even and arr[k] < arr[k + 1] when k is odd. Examples: Input: arr[] = {9, 4, 2, 10, 7,
6 min read
Find Maximum XOR value of a sub-array of size k
Given an array of integers, the task is to find maximum XOR value of a subarray of size K. Examples : Input : arr[] = {2, 5, 8 ,1 , 1 ,3} k = 3 Output : 15 Explanation : All subarrays of size k (=3) and their XOR values are: {2, 5, 8} => XOR value = 15 {5, 8, 1} => XOR value = 12 {8, 1, 1} => XOR value = 8 {1, 1, 3} => XOR value = 3 Max
7 min read
Check if matrix can be converted to another matrix by transposing square sub-matrices
Given two N X M matrices of integers. In an operation, we can transpose any square sub-matrix in matrix1. The task is to check if matrix1 can be converted to matrix2 with the given operation.Examples: Input: matrix1[][] = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9}}, matrix2[][] = { {1, 4, 7}, {2, 5, 6}, {3, 8, 9}} Output: Yes Transpose the whole matrix and
10 min read
Create matrix whose sum of diagonals in each sub matrix is even
Given a number N, the task is to create a square matrix of size N*N with values in range [1, N*N], such that the sum of each diagonal of an even sub-square matrix is even. Examples: Input: N = 3Output: 1 2 3 4 5 6 7 8 9 Explanation:For each even sub-square matrix the sum of each diagonal is a even number.1 2 4 5 sum of each diagonal is 6 and 6 i.e
5 min read