Browse curriculum

Set Matrix Zeroes (LeetCode 73)

Set Matrix Zeroes (LeetCode 73): spread every 0 in a matrix across its full row and column, in place.

Problem Understanding

Wherever an m x n integer matrix holds a 0, clear that cell's whole row and whole column to 0, modifying the matrix in-place rather than building a copy.

Strategy (O(1) Space)

We can use the first row and first column as markers.

  1. Check if first row/col originally have zeros. Store in flags.
  2. Iterate through the rest of the matrix. If matrix[i][j] == 0, mark matrix[i][0] and matrix[0][j] as 0.
  3. Iterate again to set zeros based on markers.
  4. Handle first row/col separately using flags.
  • Use matrix[i][0] to store row status.

  • Use matrix[0][j] to store col status.

Interactive Visualization

READY

0

1

2

3

0

0
1
2
0

1

3
0
5
2

2

1
3
1
5

Row 0 zero

No

Col 0 zero

No

 

Two flags remember whether column 0 and row 0 held a zero before they are reused as markers

Next

matrix[0][0] = 0: column 0 has a zero

Free preview: the first 5 of 16 steps

Matrix

Watch how we use the first row and column as makers to avoid using O(MN) extra space.

Dry Run

Matrix: [[1,1,1],[1,0,1],[1,1,1]]

Step Action State
1 Scan Row 0/Col 0 No zeroes found. Flags=False.
2 Scan Inner matrix[1][1] is 0. Mark [1][0]=0, [0][1]=0.
3 Apply Marks [1][0] is 0 -> Set Row 1 to 0. [0][1] is 0 -> Set Col 1 to 0.
4 Apply Flags Flags are False. Skip.

Result: [[1,0,1],[0,0,0],[1,0,1]]

Edge Cases & Common Mistakes

Watch out for:

  • First Row/Col Overwrite: If you don't use separate flags (firstRowZero), you might wipe out the markers needed for the rest of the matrix.

  • Order of Operations: Process inner matrix first, THEN the first row/col based on flags.

Solution

O(M * N) Time, O(1) Space.

Set Matrix Zeroes Code
1var setZeroes = function(matrix) {
2 const m = matrix.length, n = matrix[0].length;
3 let firstRowZero = false, firstColZero = false;
4
5 for(let i=0; i<m; i++) if(matrix[i][0] === 0) firstColZero = true;
6 for(let j=0; j<n; j++) if(matrix[0][j] === 0) firstRowZero = true;
7
8 for(let i=1; i<m; i++) {
9 for(let j=1; j<n; j++) {
10 if(matrix[i][j] === 0) {
11 matrix[i][0] = 0;
12 matrix[0][j] = 0;
13 }
14 }
15 }
16
17 for(let i=1; i<m; i++) {
18 for(let j=1; j<n; j++) {
19 if(matrix[i][0] === 0 || matrix[0][j] === 0) {
20 matrix[i][j] = 0;
21 }
22 }
23 }
24
25 if(firstColZero) for(let i=0; i<m; i++) matrix[i][0] = 0;
26 if(firstRowZero) for(let j=0; j<n; j++) matrix[0][j] = 0;
27};

Set Matrix Zeroes in Python, Java, C++, TypeScript and C

Set Matrix Zeroes in Python
class Solution:
    def setZeroes(self, matrix: List[List[int]]) -> None:
        m, n = len(matrix), len(matrix[0])
        first_row_has_zero = False
        first_col_has_zero = False
        
        # Check first row/col
        for i in range(m):
            if matrix[i][0] == 0:
                first_col_has_zero = True
        for j in range(n):
            if matrix[0][j] == 0:
                first_row_has_zero = True
                
        # Mark using first row/col
        for i in range(1, m):
            for j in range(1, n):
                if matrix[i][j] == 0:
                    matrix[i][0] = 0
                    matrix[0][j] = 0
                    
        # Set zeros based on marks
        for i in range(1, m):
            for j in range(1, n):
                if matrix[i][0] == 0 or matrix[0][j] == 0:
                    matrix[i][j] = 0
                    
        # Handle first row/col
        if first_col_has_zero:
            for i in range(m):
                matrix[i][0] = 0
        if first_row_has_zero:
            for j in range(n):
                matrix[0][j] = 0
Set Matrix Zeroes in Java
class Solution {
    public void setZeroes(int[][] matrix) {
        int m = matrix.length, n = matrix[0].length;
        boolean firstRowZero = false;
        boolean firstColZero = false;
        
        for(int i=0; i<m; i++) {
            if(matrix[i][0] == 0) firstColZero = true;
        }
        for(int j=0; j<n; j++) {
            if(matrix[0][j] == 0) firstRowZero = true;
        }
        
        for(int i=1; i<m; i++) {
            for(int j=1; j<n; j++) {
                if(matrix[i][j] == 0) {
                    matrix[i][0] = 0;
                    matrix[0][j] = 0;
                }
            }
        }
        
        for(int i=1; i<m; i++) {
            for(int j=1; j<n; j++) {
                if(matrix[i][0] == 0 || matrix[0][j] == 0) {
                    matrix[i][j] = 0;
                }
            }
        }
        
        if(firstColZero) {
            for(int i=0; i<m; i++) matrix[i][0] = 0;
        }
        if(firstRowZero) {
            for(int j=0; j<n; j++) matrix[0][j] = 0;
        }
    }
}
Set Matrix Zeroes in C++
class Solution {
public:
    void setZeroes(vector<vector<int>>& matrix) {
        int m = matrix.size(), n = matrix[0].size();
        bool firstRowZero = false, firstColZero = false;
        
        for(int i=0; i<m; i++) if(matrix[i][0] == 0) firstColZero = true;
        for(int j=0; j<n; j++) if(matrix[0][j] == 0) firstRowZero = true;
        
        for(int i=1; i<m; i++) {
            for(int j=1; j<n; j++) {
                if(matrix[i][j] == 0) {
                    matrix[i][0] = 0;
                    matrix[0][j] = 0;
                }
            }
        }
        
        for(int i=1; i<m; i++) {
            for(int j=1; j<n; j++) {
                if(matrix[i][0] == 0 || matrix[0][j] == 0) {
                    matrix[i][j] = 0;
                }
            }
        }
        
        if(firstColZero) for(int i=0; i<m; i++) matrix[i][0] = 0;
        if(firstRowZero) for(int j=0; j<n; j++) matrix[0][j] = 0;
    }
};
Set Matrix Zeroes in TypeScript
function setZeroes(matrix: number[][]): void {
    const m = matrix.length, n = matrix[0].length;
    let firstRowZero = false, firstColZero = false;
    
    for(let i=0; i<m; i++) if(matrix[i][0] === 0) firstColZero = true;
    for(let j=0; j<n; j++) if(matrix[0][j] === 0) firstRowZero = true;
    
    for(let i=1; i<m; i++) {
        for(let j=1; j<n; j++) {
            if(matrix[i][j] === 0) {
                matrix[i][0] = 0;
                matrix[0][j] = 0;
            }
        }
    }
    
    for(let i=1; i<m; i++) {
        for(let j=1; j<n; j++) {
            if(matrix[i][0] === 0 || matrix[0][j] === 0) {
                matrix[i][j] = 0;
            }
        }
    }
    
    if(firstColZero) for(let i=0; i<m; i++) matrix[i][0] = 0;
    if(firstRowZero) for(let j=0; j<n; j++) matrix[0][j] = 0;
};
Set Matrix Zeroes in C
void setZeroes(int** matrix, int matrixSize, int* matrixColSize) {
    int m = matrixSize;
    int n = matrixColSize[0];
    bool firstRowZero = false;
    bool firstColZero = false;
    
    for(int i=0; i<m; i++) if(matrix[i][0] == 0) firstColZero = true;
    for(int j=0; j<n; j++) if(matrix[0][j] == 0) firstRowZero = true;
    
    for(int i=1; i<m; i++) {
        for(int j=1; j<n; j++) {
            if(matrix[i][j] == 0) {
                matrix[i][0] = 0;
                matrix[0][j] = 0;
            }
        }
    }
    
    for(int i=1; i<m; i++) {
        for(int j=1; j<n; j++) {
            if(matrix[i][0] == 0 || matrix[0][j] == 0) {
                matrix[i][j] = 0;
            }
        }
    }
    
    if(firstColZero) for(int i=0; i<m; i++) matrix[i][0] = 0;
    if(firstRowZero) for(int j=0; j<n; j++) matrix[0][j] = 0;
}

More practice: DSA interview questions with answers · patterns cheat sheet

The approach, step by step

  1. Record the flags

    Check whether column 0 and row 0 contain a zero and store the answers in two booleans.

  2. Mark rows and columns

    For every inner cell that is zero, set matrix[i][0] and matrix[0][j] to zero.

  3. Clear marked cells

    For every inner cell, set it to zero if its row marker or column marker is zero.

  4. Clear row 0 and column 0

    Finally, zero column 0 and row 0 if their flags were set.

Frequently asked questions

How do you solve Set Matrix Zeroes with O(1) extra space?

Use the first row and first column as markers. When an inner cell is zero, set matrix[i][0] and matrix[0][j] to zero; a second pass then clears every inner cell whose row marker or column marker is zero.


Why do row 0 and column 0 need separate flags?

They are overwritten when they are used as markers, so two booleans record whether they held a zero before that happened. They are cleared last, after the inner cells have been set from the markers.


What is the time and space complexity of Set Matrix Zeroes?

O(m × n) time over a fixed number of passes, and O(1) extra space: two booleans, with the markers stored in the matrix itself.

Applying for software engineering roles? Free, no sign-up:

AI resume checker: match your resume to the job description