Skip to problem
←

Largest Rectangle with Equal Zeros and Ones

Hard 0 attempts

Find the largest contiguous, axis-aligned rectangular region of a binary matrix containing equal numbers of 0 and 1. Choose consecutive rows and consecutive columns; cells cannot be skipped.

Return its area, measured in cells. A rectangle may use a single row or column, or the entire matrix. If no nonempty rectangle qualifies, return 0.

Function contract

matrix is a nonempty rectangular binary matrix.

Output: Return the maximum area (number of cells) of a contiguous rectangle containing equal counts of 0 and 1. Return 0 if none exists.

Example 1

Input
matrix = [[0,0,1,1],[0,1,1,0],[1,1,1,0],[1,0,0,1]]
Output
8

Explanation: The rectangle consisting of the first two rows and all four columns has four zeros and four ones, for area 8.

Example 2

Input
matrix = [[1]]
Output
0
Constraints
  • 1 <= R, C <= 50
  • matrix is rectangular and every entry is 0 or 1.

Convert 0→-1 then Largest Zero-Sum Submatrix

Replace 0s with -1s. For each pair of rows, accumulate each column’s sum across those rows, then find the longest zero-sum interval of columns. Store the earliest index for each running sum; repeating that sum identifies a zero-sum interval. Multiply its width by the selected row count.

javascript
function largestAreaEqual(matrix) {
  const m = matrix.length, n = matrix[0].length;
  let maxArea = 0;
  for (let top = 0; top < m; top++) {
    const colSum = Array(n).fill(0);
    for (let bot = top; bot < m; bot++) {
      for (let j = 0; j < n; j++) colSum[j] += matrix[bot][j] === 0 ? -1 : 1;
      const map = new Map([[0, -1]]);
      let sum = 0;
      for (let j = 0; j < n; j++) {
        sum += colSum[j];
        if (map.has(sum)) maxArea = Math.max(maxArea, (bot-top+1) * (j - map.get(sum)));
        else map.set(sum, j);
      }
    }
  }
  return maxArea;
}

Time: O(m²n) | Space: O(n)

Loading discussion…

Saved in this browser only. Private to you.

JavaScript