26. Largest rectangular sub-matrix whose sum is 0
Last updated
Last updated
The problem can be found at the following link: Question Link
This problem, is now updated by GFG, we can solve this problem using prefix sum. Here are the steps.
Prefix Sum Matrix Construction:
A prefix sum matrix pre
is constructed from the given matrix a
.
This matrix is built by iterating through the original matrix and updating each element with the sum of the elements above and to the left.
Iterative Submatrix Search:
The code then iterates through each element of the matrix, considering it as the top-left
corner of a potential submatrix.
For each potential submatrix, it efficiently computes the sum using the prefix sum matrix.
Nested loops are used to explore all possible submatrices starting from the current element.
Submatrices are considered by varying both the bottom-right corner (x
and y
variables) and the top-left corner (i
and j
variables).
Checking for Sum Zero:
If the sum of the submatrix is zero, it checks whether the area of the current submatrix is greater than the maximum found so far (area
variable).
Updating Maximum Submatrix:
If a submatrix with a sum of zero and a larger area is found, it updates the maximum submatrix coordinates (nax
struct).
In case of a tie in area, the code implements tie-breaking conditions:
It prefers the submatrix with a smaller starting column (nax.y1
).
If the starting columns are the same, it prefers the submatrix with a larger width (nax.x2 - nax.x1
).
Result Construction:
After iterating through all possible submatrices, it constructs the result matrix based on the coordinates of the maximum submatrix.
Handling No Solution Case:
If no submatrix with a sum of zero is found, an empty matrix is returned.
Time Complexity: (O(n^4))
- The nested loops result in a time complexity of (O(n^2))
, and for each sub-matrix, we calculate the sum in (O(n^2))
time.
Auxiliary Space Complexity: (O(n^2))
- Additional space is required for the prefix sum matrix.
For discussions, questions, or doubts related to this solution, please visit our discussion section. We welcome your input and aim to foster a collaborative learning environment.
If you find this solution helpful, consider supporting us by giving a ⭐ star
to the getlost01/gfg-potd repository.