![]() |
VOOZH | about |
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
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.
Implementation:
(Top, Left): (0, 0) (Bottom, Right): (3, 1) Area: 8 sq.units
Time Complexity: O(n3) Auxiliary Space: O(n)