Largest area rectangular sub-matrix with equal number of 1’s and 0’s

Pattern: 2D grid DP

medium

Treat 0 as -1. A rectangle has equal 0s and 1s exactly when its sum is 0. Fix the top and bottom rows, add up each column between them, and find the widest run of columns with sum 0 using prefix sums in a hash map.

The problem

Given a binary matrix, return the area of the largest rectangle that contains as many 0s as 1s, or 0 if there is none. GFG prints the rectangle; this guide returns its area. The catalogue has no practice link for this one.

Think first

  • How can 'equal counts' become a sum condition?
  • If the rows are fixed, what 1D problem is left?
  • How do you find the longest zero-sum subarray?

Hints

    Brute force, and why it fails

    Try every rectangle and count: O(R² × C²) with prefix sums, worse without.

    The key insight

    Fixing two rows turns the problem into the 1D zero-sum subarray, which a hash map solves in O(C).

    Dry run

    Rows 0..3 of the 4 × 4 example, as ±1, give column sums 0, 0, 2, 0... the widest zero-sum run for some pair of rows is found.

    Step 1 of 2

    The plan

    for top: col = zeros; for bottom: add row bottom (as ±1) to col
      longest zero-sum run of col via first-seen prefix sums; area = rows × width
    

    Complexity

    Time
    O(R² × C)
    Space
    O(C)

    Every pair of rows, with a linear scan of the columns.

    Edge cases

    • All 1s: 0.
    • One cell: 0.
    • A 1 × 2 [0, 1]: 2.
    I've built my logic, show the code

    Java

    import java.util.*;
    
    class Solution {
        public int maxEqualArea(int[][] mat) {
            int R = mat.length, C = mat[0].length, best = 0;
            for (int top = 0; top < R; top++) {
                int[] col = new int[C];             // column sums between rows top and bottom
                for (int bottom = top; bottom < R; bottom++) {
                    for (int c = 0; c < C; c++) col[c] += (mat[bottom][c] == 1 ? 1 : -1);
                    Map<Integer, Integer> first = new HashMap<>();   // prefix sum -> earliest column where it was seen
                    first.put(0, -1);
                    int sum = 0;
                    for (int c = 0; c < C; c++) {   // a repeated prefix sum means the columns between sum to 0
                        sum += col[c];
                        Integer start = first.get(sum);
                        if (start != null) best = Math.max(best, (bottom - top + 1) * (c - start));
                        else first.put(sum, c);
                    }
                }
            }
            return best;
        }
    }

    C++

    class Solution {
    public:
        int maxEqualArea(vector<vector<int>>& mat) {
            int R = static_cast<int>(mat.size()), C = static_cast<int>(mat[0].size()), best = 0;
            for (int top = 0; top < R; top++) {
                vector<int> col(C, 0);              // column sums between rows top and bottom
                for (int bottom = top; bottom < R; bottom++) {
                    for (int c = 0; c < C; c++) col[c] += (mat[bottom][c] == 1 ? 1 : -1);
                    unordered_map<int, int> first;  // prefix sum -> earliest column where it was seen
                    first[0] = -1;
                    int sum = 0;
                    for (int c = 0; c < C; c++) {   // a repeated prefix sum means the columns between sum to 0
                        sum += col[c];
                        auto it = first.find(sum);
                        if (it != first.end()) best = max(best, (bottom - top + 1) * (c - it->second));
                        else first[sum] = c;
                    }
                }
            }
            return best;
        }
    };

    Python

    class Solution:
        def maxEqualArea(self, mat: list[list[int]]) -> int:
            R, C, best = len(mat), len(mat[0]), 0
            for top in range(R):
                col = [0] * C                       # column sums between rows top and bottom
                for bottom in range(top, R):
                    for c in range(C):
                        col[c] += 1 if mat[bottom][c] else -1   # a 0 counts as -1
                    first, s = {0: -1}, 0             # prefix sum -> earliest column where it was seen
                    for c in range(C):              # a repeated prefix sum means the columns between sum to 0
                        s += col[c]
                        if s in first:
                            best = max(best, (bottom - top + 1) * (c - first[s]))
                        else:
                            first[s] = c
            return best

    Common mistakes

    • Counting 0 as 0, not -1.
    • Updating the first-seen position after it is set.

    Similar problems