73. Set Matrix Zeroes
Difficulty: Medium
- Tags: Array
, Matrix
, Simulation
Problem Statement 📜
Given an m x n
integer matrix matrix
, if an element is 0
, set its entire row and column to 0
's.
You must perform this operation in-place, without using extra space.
Examples 🌟
🔹 Example 1:
Input:
Output:
🔹 Example 2:
Input:
Output:
Constraints ⚙️
m == matrix.length
n == matrix[0].length
1 <= m, n <= 200
-2^31 <= matrix[i][j] <= 2^31 - 1
Follow-up 🤔
A straightforward solution using O(mn) space is probably not the best approach.
A simple improvement uses O(m + n) space, but can you devise a solution using constant space?
Solution 💡
To solve this problem efficiently:
Naive Approach:
Use two auxiliary arrays
rows
andcols
to store which rows and columns need to be set to0
. This approach uses extra space.
Optimized Approach:
Use the matrix itself to track which rows and columns need to be zeroed.
Use the first row and first column of the matrix to store the state of other rows and columns.
If
matrix[i][j]
is0
, mark the first row and first column to indicate that the entire row and column need to be set to zero.
Java Solution
Explanation of the Solution
Step 1: Check the first row and first column:
If any element in the first row or column is
0
, mark therowZero
orcolZero
flag astrue
.
Step 2: Mark rows and columns to be zeroed:
Traverse the matrix starting from
matrix[1][1]
and mark the first row and first column to indicate that the corresponding row and column should be set to0
.
Step 3: Zero out cells:
Traverse the matrix again to set cells to
0
based on the marks in the first row and column.
Step 4: Handle the first row and first column:
Set the first row and first column to
0
if needed (based on the flagsrowZero
andcolZero
).
Time Complexity ⏳
O(m * n):
We traverse the matrix multiple times, each traversal takes
O(m * n)
.
Space Complexity 💾
O(1):
We do not use any extra space for storing row or column markers, making this solution constant space.
You can find the full solution here.
Last updated