Introduction
Set Matrix Zeroes means:
- if any matrix cell contains 0
- its entire row and column become 0
The task is to:
- modify matrix efficiently
- avoid unnecessary extra space
- update rows and columns correctly
Example:
Input Matrix:1 1 1
1 0 1
1 1 1
Output Matrix: 1 0 1
0 0 0
1 0 1
Explanation:
Cell:matrix[1][1] = 0
Entire row and column become zero.
This problem is one of the most important applications of:
In-Place Matrix Marking Constraints
1 <= Rows, Columns <= 10^3 Approach 1 : Brute Force (Using Extra Arrays)
Explanations:
Explanation:
The idea is:
- store rows containing zero
- store columns containing zero
Steps:
- Traverse matrix.
- Mark rows and columns.
- Update matrix.
This approach works but:
- uses extra space
So in-place marking is preferred.
Dry Run
Matrix:
1 1 1
1 0 1
1 1 1
Zero found: at position (1,1)
Updated Matrix:
1 0 1
0 0 01 0 1
Practice :
Complexity Analysis :
Time Complexity:- O(rows × cols)Explanation :
Matrix is traversed multiple times.
Space Complexity:- O(rows + cols)
Explanation : Extra row & column storage is used.
Approach 2 : Optimal Solution(In-Place Marking)
Explanations:
Explanation:
This is the most optimized and interview-preferred solution.
The idea is:
- use first row and column as markers
- avoid extra arrays
This reduces:
- extra space usage
Dry Run
Matrix:
1 1 1
1 0 1
1 1 1
Mark:
first row & column
Update rows and columns
Final Matrix: 1 0 1
0 0 01 0 1
Practice :