Set Matrix Zeroes In Place in DSA Rust - Time & Space Complexity
We want to understand how the time needed to set matrix zeroes changes as the matrix size grows.
How does the number of steps grow when the matrix gets bigger?
Analyze the time complexity of the following code snippet.
fn set_zeroes(matrix: &mut Vec>) {
let rows = matrix.len();
let cols = matrix[0].len();
let mut col_zero = false;
for i in 0..rows {
if matrix[i][0] == 0 {
col_zero = true;
}
for j in 1..cols {
if matrix[i][j] == 0 {
matrix[i][0] = 0;
matrix[0][j] = 0;
}
}
}
for i in 1..rows {
for j in 1..cols {
if matrix[i][0] == 0 || matrix[0][j] == 0 {
matrix[i][j] = 0;
}
}
}
if matrix[0][0] == 0 {
for j in 0..cols {
matrix[0][j] = 0;
}
}
if col_zero {
for i in 0..rows {
matrix[i][0] = 0;
}
}
}
This code sets entire rows and columns to zero if any element in them is zero, using the matrix itself to store flags.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Nested loops scanning rows and columns of the matrix.
- How many times: Each nested loop runs roughly once over all elements, so about rows x columns times.
As the matrix size grows, the number of steps grows roughly with the total number of elements.
| Input Size (n x n) | Approx. Operations |
|---|---|
| 10 x 10 | About 200 (2 x 10 x 10) |
| 100 x 100 | About 20,000 (2 x 100 x 100) |
| 1000 x 1000 | About 2,000,000 (2 x 1000 x 1000) |
Pattern observation: The operations grow roughly with the square of the matrix size, doubling the size quadruples the work.
Time Complexity: O(m x n)
This means the time needed grows proportionally to the total number of elements in the matrix.
[X] Wrong: "The time complexity is O((m x n)²) because of nested loops inside nested loops."
[OK] Correct: The loops are sequential, not nested inside each other repeatedly; each element is visited a constant number of times, so the total work is linear in the number of elements.
Understanding this time complexity helps you explain how your solution scales with input size, a key skill in interviews.
"What if we used extra space to store zero positions 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 asks to set entire rows and columns to zero if any element in them is zero, modifying the matrix directly without extra space.Step 2: Differentiate from other options
Options A, B, and C do not match the problem's goal of modifying rows and columns based on zero elements.Final Answer:
Modify the matrix so that if an element is 0, its entire row and column become 0 without using extra space. -> Option CQuick Check:
Goal = Modify matrix rows and columns in place [OK]
- Thinking only to count zeros
- Trying to use extra memory
- Confusing with sorting or replacing zeros
matrix with 3 rows and 3 columns initialized to 1?Solution
Step 1: Identify mutable declaration
To modify the matrix later, it must be declared mutable usinglet mut.Step 2: Correct 2D vector initialization
The syntaxvec![vec![1; 3]; 3]creates a 3x3 vector filled with 1s. Options B and D are invalid syntax. let matrix = vec![vec![1; 3]; 3]; lacks mut.Final Answer:
let mut matrix = vec![vec![1; 3]; 3]; -> Option AQuick Check:
Mutable 2D vector with correct syntax = let mut matrix = vec![vec![1; 3]; 3]; [OK]
let mut and nested vec! for 2D vectors [OK]- Forgetting
mutkeyword - Using invalid vector syntax
- Confusing 1D and 2D vector initialization
set_zeroes(&mut matrix)?
fn set_zeroes(matrix: &mut Vec) {
let rows = matrix.len();
let cols = matrix[0].len();
let mut row_zero = false;
for i in 0..rows {
if matrix[i][0] == 0 {
row_zero = true;
}
for j in 1..cols {
if matrix[i][j] == 0 {
matrix[i][0] = 0;
matrix[0][j] = 0;
}
}
}
for i in 1..rows {
for j in 1..cols {
if matrix[i][0] == 0 || matrix[0][j] == 0 {
matrix[i][j] = 0;
}
}
}
if matrix[0][0] == 0 {
for j in 0..cols {
matrix[0][j] = 0;
}
}
if row_zero {
for i in 0..rows {
matrix[i][0] = 0;
}
}
}
fn main() {
let mut matrix = vec![
vec![1, 1, 1],
vec![1, 0, 1],
vec![1, 1, 1],
];
set_zeroes(&mut matrix);
for row in matrix {
println!("{:?}", row);
}
}Solution
Step 1: Identify zero positions and mark rows and columns
The zero is at position (1,1). The first loop marks row 1 and column 1 by setting matrix[1][0] and matrix[0][1] to zero.Step 2: Set zeros based on marks
The second loop sets elements to zero if their row or column is marked. This changes matrix[0][1], matrix[1][0..2], and matrix[2][1] to zero.Final Answer:
[[1, 0, 1], [0, 0, 0], [1, 0, 1]] -> Option AQuick Check:
Zero at (1,1) affects row 1 and column 1 [OK]
- Not marking first row and column correctly
- Overwriting zeros too early
- Ignoring the first column zero flag
fn set_zeroes(matrix: &mut Vec) {
let rows = matrix.len();
let cols = matrix[0].len();
for i in 0..rows {
for j in 0..cols {
if matrix[i][j] == 0 {
for k in 0..rows {
matrix[k][j] = 0;
}
for l in 0..cols {
matrix[i][l] = 0;
}
}
}
}
}Solution
Step 1: Analyze matrix modification during iteration
The function sets zeros immediately when it finds a zero, which changes the matrix during iteration.Step 2: Understand effect of immediate modification
This causes new zeros to be found in later iterations, incorrectly zeroing more rows and columns than intended.Final Answer:
It modifies the matrix while iterating, causing incorrect zero propagation. -> Option BQuick Check:
Immediate zeroing during iteration causes errors [OK]
- Changing matrix elements inside nested loops
- Not using markers to delay zeroing
- Ignoring matrix size checks
[ [1, 2, 0, 4], [5, 6, 7, 8], [9, 0, 11, 12], [13, 14, 15, 16] ]Using the in-place algorithm that uses the first row and column as markers, what will be the matrix after applying
set_zeroes?Solution
Step 1: Mark rows and columns using first row and column
Zeros at (0,2) and (2,1) mark row 0, row 2, column 2, and column 1 as zero.Step 2: Update matrix based on markers
Set all elements in rows 0 and 2, and columns 1 and 2 to zero. Also, since matrix[0][0] is zero (due to marking), first row is zeroed. First column is zeroed only where rows are marked since no original first column zero.Final Answer:
[[0, 0, 0, 0], [5, 0, 0, 8], [0, 0, 0, 0], [13, 0, 0, 16]] -> Option DQuick Check:
First row and column mark zeros correctly [OK]
- Forgetting to zero first row or column
- Not marking all affected rows and columns
- Incorrectly zeroing unrelated cells
Ready to prove it?
Pass the test and this pattern moves unknown
