1. Full Matrix Clone & Reference
Intuition
Create an M x N copy of the matrix to read original zero locations without interference, and write zeroes to the original matrix.
Algorithm
- 1. Allocate a duplicate matrix clone of size M x N and copy all values from matrix.
- 2. Iterate over each cell (r, c) in the clone matrix.
- 3. If clone[r][c] == 0, iterate across row r (0..N-1) and column c (0..M-1) in the original matrix and set matrix[r][k] = 0 and matrix[k][c] = 0.
- 4. The original matrix is now updated without any chain-reaction corruption.
Brute Force Sentinel Replacement Scan
2 of 2 questions left todayPhase 1 — Trigger sentinel marking for row 1 and column 1: Step 1: Traverse matrix cells
Phase 1 — Trigger sentinel marking for row 1 and column 1: Step 1: Traverse matrix cells. At coordinate (1, 1), a zero is detected.
#include <iostream>#include <vector>#include <string>#include <algorithm>#include <unordered_map>#include <unordered_set>#include <queue>#include <stack>#include <numeric>#include <climits> using namespace std; class Solution {public: void setZeroes(vector<vector<int>>& matrix) { int m = matrix.size(); int n = matrix[0].size(); vector<vector<int>> clone = matrix; for (int r = 0; r < m; ++r) { for (int c = 0; c < n; ++c) { if (clone[r][c] == 0) { for (int k = 0; k < n; ++k) matrix[r][k] = 0; for (int k = 0; k < m; ++k) matrix[k][c] = 0; } } } }}; int main() { Solution sol; vector<vector<int>> matrix = {{1, 1, 1}, {1, 0, 1}, {1, 1, 1}}; sol.setZeroes(matrix); cout << "Matrix After setZeroes:" << endl; for (const auto& row : matrix) { for (int val : row) cout << val << " "; cout << endl; } return 0;}Time & Space Complexity
- Time complexity:
O(M * N * (M + N))— We scan M x N cells. For each zero found, we perform O(M + N) work to overwrite the row and column in the original matrix. In the worst case (all zeroes), this takes O(M * N * (M + N)) time. - Space complexity:
O(M * N)— Requires an auxiliary matrix clone of dimensions M x N, consuming O(M * N) additional memory.
Why Brute Force Doesn't Scale:
In an M x N grid, we only need to store M boolean flags for rows and N boolean flags for columns. Instead of creating new arrays, matrix[0][c] has N cells and matrix[r][0] has M cells. By reusing these existing border cells as our flags and reserving a single scalar variable for column 0, auxiliary memory drops to zero.
For a 200 x 200 grid: Brute force uses 40,000 ints (~160 KB). Optimal uses 0 extra bytes.