Set Matrix Zeroes In Place in DSA C++ - Time & Space Complexity
We want to understand how the time needed to set matrix zeroes grows as the matrix size increases.
Specifically, how does the number of steps change when we mark rows and columns to zero in place?
Analyze the time complexity of the following code snippet.
void setZeroes(std::vector<std::vector<int>>& matrix) {
int rows = matrix.size();
int cols = matrix[0].size();
bool firstColZero = false;
for (int i = 0; i < rows; i++) {
if (matrix[i][0] == 0) firstColZero = true;
for (int j = 1; j < cols; j++) {
if (matrix[i][j] == 0) {
matrix[i][0] = 0;
matrix[0][j] = 0;
}
}
}
for (int i = 1; i < rows; i++) {
for (int j = 1; j < cols; j++) {
if (matrix[i][0] == 0 || matrix[0][j] == 0) {
matrix[i][j] = 0;
}
}
}
if (matrix[0][0] == 0) {
for (int j = 0; j < cols; j++) matrix[0][j] = 0;
}
if (firstColZero) {
for (int i = 0; i < rows; i++) matrix[i][0] = 0;
}
}
This code sets entire rows and columns to zero if any element in them is zero, using the first row and column as markers.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Nested loops traversing the matrix rows and columns.
- How many times: Each nested loop runs approximately rows x cols times.
As the matrix size grows, the number of operations grows roughly with the total number of elements.
| Input Size (rows x cols) | Approx. Operations |
|---|---|
| 10 x 10 = 100 | About 300 steps (3 passes over matrix) |
| 100 x 100 = 10,000 | About 30,000 steps |
| 1000 x 1000 = 1,000,000 | About 3,000,000 steps |
Pattern observation: Operations grow linearly with the number of elements in the matrix.
Time Complexity: O(m x n)
This means the time needed grows proportionally to the total number of elements in the matrix.
[X] Wrong: "Since we use the first row and column as markers, the time complexity is less than scanning the whole matrix twice."
[OK] Correct: Even with markers, we still scan almost every element multiple times, so the time grows with the total elements.
Understanding this time complexity helps you explain how your solution scales with matrix size, a key skill in interviews.
"What if we used extra space to store zero rows and columns instead of marking in place? How would the time complexity change?"
Practice
Set Matrix Zeroes In Place problem?Solution
Step 1: Understand the problem requirement
The problem requires changing the matrix so that any row or column containing a zero is set entirely to zero.Step 2: Note the in-place constraint
We must do this without using extra space for another matrix or large data structures.Final Answer:
Modify the matrix so that if an element is 0, its entire row and column become 0 without using extra space. -> Option DQuick Check:
In-place zeroing = Modify matrix rows and columns [OK]
- Using extra space like another matrix
- Only zeroing the element itself, not row and column
- Not handling the in-place requirement
Set Matrix Zeroes In Place problem?Solution
Step 1: Understand 2D vector declaration
To create a matrix with 'rows' rows and 'cols' columns, use vector of vectors with inner vector size 'cols'.Step 2: Check each option
std::vector matrix(rows, std::vector<int>(cols)); correctly creates a vector of vectors with 'rows' outer vectors and 'cols' inner vectors each.Final Answer:
std::vector matrix(rows, std::vector<int>(cols)); -> Option CQuick Check:
Correct 2D vector syntax = std::vector matrix(rows, std::vector<int>(cols)); [OK]
- Using single vector with two sizes incorrectly
- Swapping rows and columns in inner vector
- Using array syntax instead of vector
Set Matrix Zeroes In Place?
std::vector matrix = {
{1, 2, 3},
{4, 0, 6},
{7, 8, 9}
};
// Assume correct in-place zeroing function is called here
setZeroes(matrix);
// Print matrixSolution
Step 1: Identify zero positions
The zero is at position (1,1) (second row, second column).Step 2: Set entire row and column to zero
Row 1 becomes [0,0,0], column 1 becomes zero in rows 0 and 2, so matrix becomes [[1,0,3],[0,0,0],[7,0,9]].Final Answer:
[[1, 0, 3], [0, 0, 0], [7, 0, 9]] -> Option BQuick Check:
Zero at (1,1) zeroes row 1 and column 1 [OK]
- Zeroing entire matrix instead of row and column
- Not zeroing column correctly
- Leaving original zero row unchanged
Set Matrix Zeroes In Place. What is the main error?
void setZeroes(std::vector& matrix) {
int rows = matrix.size();
int cols = matrix[0].size();
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
if (matrix[i][j] == 0) {
for (int k = 0; k < cols; k++) matrix[i][k] = 0;
for (int k = 0; k < rows; k++) matrix[k][j] = 0;
}
}
}
}Solution
Step 1: Analyze modification during iteration
The code sets zeros immediately when a zero is found, changing matrix during iteration.Step 2: Understand side effects
This causes new zeros to appear and cause more zeroing, leading to incorrect results.Final Answer:
Modifying matrix inside loops causes multiple zeroing and incorrect results. -> Option AQuick Check:
Immediate modification causes cascading zeroing [OK]
- Changing matrix while scanning causes wrong zeroing
- Not using markers or flags to delay zeroing
- Ignoring empty matrix edge cases
Solution
Step 1: Use first row and column as markers
Mark zeros found in first row and column to remember which rows and columns to zero later.Step 2: Update matrix based on markers
After marking, zero out rows and columns except first row and column, then handle first row and column separately.Final Answer:
Use first row and first column as markers to store zero flags, then update matrix accordingly. -> Option AQuick Check:
In-place marking with first row/column = Use first row and first column as markers to store zero flags, then update matrix accordingly. [OK]
- Using extra space violating in-place rule
- Zeroing immediately causing cascading errors
- Not handling first row and column separately
Ready to prove it?
Pass the test and this pattern moves unknown
