VOOZH about

URL: https://www.geeksforgeeks.org/dsa/set-matrix-rows-and-columns-to-zeroes/

⇱ Set Matrix Rows and Columns to Zeroes - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Set Matrix Rows and Columns to Zeroes

Last Updated : 8 Mar, 2026

Given a matrix mat[][] of size nxm, the task is to update the matrix such that if an element is zero, set its entire row and column to zeroes.

Examples:

Input: mat[][] = [[1, -1, 1],
[-1, 0, 1],
[1, -1, 1]]
Output: [[1, 0, 1],
[0, 0, 0],
[1, 0, 1]]
Explanation: mat[1][1] = 0, so all elements in row 1 and column 1 are updated to zeroes.

Input: mat[][] = [[0, 1, 2, 0],
[3, 4, 0, 2],
[1, 3, 1, 5]]
Output: [[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 3, 0, 0]]
Explanation: mat[0][0], mat[1][2] and mat[0][3] are 0s, so all elements in row 0, row 1, column 0, column 2 and column 3 are updated to zeroes.

[Naive Approach] Using Two Auxiliary Arrays - O(n*m) Time and O(n+m) Space

The idea is to maintain two additional arrays, say rows[] and cols[] to store the rows and columns which contains at least one element equal to 0. So, first traverse the entire matrix and for each mat[i][j] = 0, mark rows[i] = true and cols[j] = true. Now in the second traversal, for each cell (i, j), if either rows[i] or cols[j] is marked as true, update mat[i][j] = 0 else continue to the next cell.

Illustration:



Output
0 0 0 0 
0 0 0 0 
0 3 0 0 

[Expected Approach] Using First Row and Column - O(n*m) Time and O(1) Space

In the previous approach we took two arrays to store the row's and column's status. Now instead of two auxiliary arrays, we can use the first row and first column of mat[][] to store which row elements and column elements are to be marked as zeroes.

So if the first cell of a row is set to 0, then all cells of that row should be updated with 0. Similarly, if the first cell of a column is set to 0, then all cells of that column should be updated to 0. Since cell (0, 0) is first cell of the first row as well as the first column, so maintain another variable, say c0 to store the status of the first column and cell(0, 0) will store the status of the first row.

Step By Step Algorithm:

  • Traverse the matrix, and for each cell (i, j) such that mat[i][j] = 0, mark mat[i][0] and mat[0][j] as 0. Note: If i = 0, mark mat[0][0] as 0 and if j = 0, mark c0 as 0.
  • Again traverse the matrix from (1, 1) to (n-1, m-1), and set mat[i][j] = 0 if either mat[i][0] = 0 or mat[0][j] = 0.
  • Finally, update the first row and first column: If mat[0][0] = 0, set all elements in first row to 0 and if c0 = 0, set all elements in the first column to 0.

Illustration:


Output
0 0 0 0 
0 0 0 0 
0 3 0 0 


Comment