Set Matrix Zeroes - Optimal Approach

Set Matrix Zeroes - Optimal Approach

Algorithm Steps

  1. Given a 2D matrix mat.
  2. Use the first row and first column as markers to indicate if a row or column should be set to zero.
  3. Check if the first row and first column themselves contain any zero using two separate flags.
  4. Traverse the rest of the matrix:
  5. → If any element is 0, mark its row and column in the first row and column.
  6. Traverse the matrix again (excluding first row and column):
  7. → If mat[i][0] == 0 or mat[0][j] == 0, set mat[i][j] = 0.
  8. Finally, update the first row and first column based on the flags.

Set Matrix Zeroes Using Constant Space Code

Python
JavaScript
Java
C++
C
def set_zeroes(matrix):
    rows, cols = len(matrix), len(matrix[0])
    first_row_zero = any(matrix[0][j] == 0 for j in range(cols))
    first_col_zero = any(matrix[i][0] == 0 for i in range(rows))

    for i in range(1, rows):
        for j in range(1, cols):
            if matrix[i][j] == 0:
                matrix[i][0] = 0
                matrix[0][j] = 0

    for i in range(1, rows):
        for j in range(1, cols):
            if matrix[i][0] == 0 or matrix[0][j] == 0:
                matrix[i][j] = 0

    if first_row_zero:
        for j in range(cols):
            matrix[0][j] = 0

    if first_col_zero:
        for i in range(rows):
            matrix[i][0] = 0

    return matrix

# Sample Input
mat = [[1,1,1],[1,0,1],[1,1,1]]
print("Updated Matrix:", set_zeroes(mat))