Taro Logo

Set Matrix Zeroes

Medium
Apple logo
Apple
2 views
Topics:
Arrays

Given an m x n integer matrix matrix, if an element is 0, set its entire row and column to 0's. You must do it in place.

For example:

Example 1:

Input:

[ [1, 1, 1],
  [1, 0, 1],
  [1, 1, 1] ]

Output:

[ [1, 0, 1],
  [0, 0, 0],
  [1, 0, 1] ]

Example 2:

Input:

[ [0, 1, 2, 0],
  [3, 4, 5, 2],
  [1, 3, 1, 5] ]

Output:

[ [0, 0, 0, 0],
  [0, 4, 5, 0],
  [0, 3, 1, 0] ]

Constraints:

  • m == matrix.length
  • n == matrix[0].length
  • 1 <= m, n <= 200
  • -2^31 <= matrix[i][j] <= 2^31 - 1

Can you implement an algorithm to solve this problem with O(1) space complexity?

Solution


Understanding the Problem

The problem requires modifying a given m x n matrix in-place. If any element in the matrix is 0, its entire row and column must be set to 0. The main challenge lies in achieving this modification efficiently, ideally with constant space complexity.

Brute Force Solution

A straightforward, but not space-efficient, approach involves using two auxiliary arrays (or sets) of sizes m and n to track the rows and columns that contain at least one 0. After identifying these rows and columns, the matrix can be iterated through again, setting elements to 0 based on the information in the auxiliary data structures.

Algorithm

  1. Initialize two boolean arrays, row of size m and col of size n, with all elements set to false. These arrays will record whether a row or column needs to be zeroed out.
  2. Iterate through the input matrix. If matrix[i][j] is 0, set row[i] = true and col[j] = true.
  3. Iterate through the matrix again. If row[i] is true OR col[j] is true, set matrix[i][j] = 0.

Code (Python)

def set_matrix_zero_brute_force(matrix):
    m = len(matrix)
    n = len(matrix[0])

    row = [False] * m
    col = [False] * n

    for i in range(m):
        for j in range(n):
            if matrix[i][j] == 0:
                row[i] = True
                col[j] = True

    for i in range(m):
        for j in range(n):
            if row[i] or col[j]:
                matrix[i][j] = 0

Complexity Analysis

  • Time Complexity: O(m * n), as we iterate through the matrix twice.
  • Space Complexity: O(m + n), due to the row and col arrays.

Optimal Solution: In-Place Modification

A more efficient solution uses the first row and first column of the matrix itself to store the information about which rows and columns need to be zeroed out. This reduces the space complexity to O(1).

Algorithm

  1. Use two flags, row_has_zero and col_has_zero, to check if the first row and first column initially contain any zeros.
  2. Iterate through the matrix (excluding the first row and first column). If matrix[i][j] is 0, set matrix[i][0] = 0 and matrix[0][j] = 0.
  3. Iterate through the matrix again (excluding the first row and first column). If matrix[i][0] or matrix[0][j] is 0, set matrix[i][j] = 0.
  4. Finally, zero out the first row and first column based on the row_has_zero and col_has_zero flags.

Code (Python)

def set_matrix_zero_optimal(matrix):
    m = len(matrix)
    n = len(matrix[0])

    row_has_zero = False
    col_has_zero = False

    # Check if first row has zero
    for j in range(n):
        if matrix[0][j] == 0:
            row_has_zero = True
            break

    # Check if first column has zero
    for i in range(m):
        if matrix[i][0] == 0:
            col_has_zero = True
            break

    # Mark zeros on first row and first column
    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

    # Use marks to set elements to zero (except first row and column)
    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

    # Set first row and column to zero if needed
    if row_has_zero:
        for j in range(n):
            matrix[0][j] = 0

    if col_has_zero:
        for i in range(m):
            matrix[i][0] = 0

Complexity Analysis

  • Time Complexity: O(m * n), as we iterate through the matrix a few times.
  • Space Complexity: O(1), as we are using constant extra space.

Edge Cases

  • Empty Matrix: If the input matrix is empty (either m = 0 or n = 0), no operations are needed. The code should handle this gracefully.
  • Matrix with one row or one column: The algorithm still applies correctly. The flags row_has_zero and col_has_zero will appropriately handle these cases.
  • All Zeros: If the entire matrix is filled with zeros, the algorithm correctly sets the entire matrix to zeros.