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

Given a binary matrix. The problem is to find the largest area rectangular sub-matrix with equal number of 1’s and 0’s.

Examples:

```Input : mat[][] = { {0, 0, 1, 1},
{0, 1, 1, 0},
{1, 1, 1, 0},
{1, 0, 0, 1} }
Output : 8 sq. units
(Top, left): (0, 0)
(Bottom, right): (3, 1)

Input : mat[][] = { {0, 0, 1, 1},
{0, 1, 1, 1} }
Output : 6 sq. units
```

## Recommended: Please try your approach on {IDE} first, before moving on to the solution.

The naive solution for this problem is to check every possible rectangle in given 2D array by counting the total number of 1’s and 0’s in that rectangle. This solution requires 4 nested loops and time complexity of this solution would be O(n^4).

An efficient solution is based on Largest rectangular sub-matrix whose sum is 0 which reduces the time complexity to O(n^3). First of all consider every ‘0’ in the matrix as ‘-1’. Now, the idea is to reduce the problem to 1-D array. We fix the left and right columns one by one and find the largest sub-array with 0 sum contiguous rows for every left and right column pair. We basically find top and bottom row numbers (which have sum zero) for every fixed left and right column pair. To find the top and bottom row numbers, calculate sum of elements in every row from left to right and store these sums in an array say temp[]. So temp[i] indicates sum of elements from left to right in row i. If we find largest subarray with 0 sum in temp[], we can get the index positions of rectangular sub-matrix with sum equal to 0 (i.e. having equal number of 1’s and 0’s). With this process we can find the largest area rectangular sub-matrix with sum equal to 0 (i.e. having equal number of 1’s and 0’s). We can use Hashing technique to find maximum length sub-array with sum equal to 0 in 1-D array in O(n) time.

 `// C++ implementation to find largest area rectangular ` `// submatrix with equal number of 1's and 0's ` `#include ` ` `  `using` `namespace` `std; ` ` `  `#define MAX_ROW 10 ` `#define MAX_COL 10 ` ` `  `// This function basically finds largest 0 ` `// sum subarray in arr[0..n-1]. If 0 sum ` `// does't exist, then it returns false. Else ` `// it returns true and sets starting and ` `// ending indexes as start and end. ` `bool` `subArrWithSumZero(``int` `arr[], ``int` `&start,  ` `                              ``int` `&end, ``int` `n) ` `{ ` `    ``// to store cumulative sum ` `    ``int` `sum[n]; ` `     `  `    ``// Initialize all elements of sum[] to 0 ` `    ``memset``(sum, 0, ``sizeof``(sum)); ` `     `  `    ``// map to store the indexes of sum ` `    ``unordered_map<``int``, ``int``> um; ` `     `  `    ``// build up the cumulative sum[] array ` `    ``sum = arr; ` `    ``for` `(``int` `i=1; i

Output:

```(Top, Left): (0, 0)
(Bottom, Right): (3, 1)
Area: 8 sq.units
```

Time Complexity: O(n3)
Auxiliary Space: O(n)