27. Set Matrix Zeroes
β GFG solution to the Set Matrix Zeroes problem: modify matrix to set entire rows and columns to zero when encountering a zero element using optimal space approach. π
The problem can be found at the following link: π Question Link
π§© Problem Description
You are given a 2D matrix mat[][] of size n x m. The task is to modify the matrix such that if mat[i][j] is 0, all the elements in the i-th row and j-th column are set to 0.
The challenge is to solve this in-place without using extra space proportional to the matrix size.
π Examples
Example 1
Input: mat = [[1, 1, 1], [1, 0, 1], [1, 1, 1]]
Output: [[1, 0, 1], [0, 0, 0], [1, 0, 1]]
Explanation: mat[1][1] = 0, so all elements in row 1 and column 1 are updated to zeroes.Example 2
Input: mat = [[0, 1, 2, 0], [3, 4, 5, 2], [1, 3, 1, 5]]
Output: [[0, 0, 0, 0], [0, 4, 5, 0], [0, 3, 1, 0]]
Explanation: mat[0][0] and mat[0][3] are 0s, so all elements in row 0, column 0 and column 3 are updated to zeroes.π Constraints
$1 \le n, m \le 500$
$-2^{31} \le \text{mat}[i][j] \le 2^{31} - 1$
β
My Approach
The optimal approach uses the first row and first column as markers to track which rows and columns should be zeroed, achieving O(1) space complexity:
In-Place Flagging with Boundary Tracking
Track Boundary States:
Use boolean flags
firstRowandfirstColto remember if the first row or first column originally contained zeros.This prevents confusion when using them as markers.
Mark Using Matrix Itself:
Iterate through the matrix starting from
(1,1).When finding a zero at
mat[i][j], markmat[i][0] = 0andmat[0][j] = 0.This uses the first row and column as a "marking system".
Apply Zeros Based on Markers:
For each cell
mat[i][j](excluding first row/column), if eithermat[i][0]ormat[0][j]is zero, setmat[i][j] = 0.
Handle Boundaries:
If
firstRowwas true, zero out the entire first row.If
firstColwas true, zero out the entire first column.
Why This Works:
We use the matrix's own space to store marking information.
By handling boundaries separately, we avoid overwriting critical marker data.
π Time and Auxiliary Space Complexity
Expected Time Complexity: O(nΓm), where n and m are the dimensions of the matrix. We traverse the matrix a constant number of times (3-4 passes).
Expected Auxiliary Space Complexity: O(1), as we only use two boolean variables for boundary tracking, regardless of matrix size.
π§βπ» Code (C++)
π§βπ» Code (Java)
π Code (Python)
π§ Contribution and Support
For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: π¬ Any Questions?. Let's make this learning journey more collaborative!
β If you find this helpful, please give this repository a star! β
πVisitor Count
Last updated