Taro Logo

Set Matrix Zeroes

#182 Most AskedMedium
0 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.

Example 1:

Input: matrix = [[1,1,1],[1,0,1],[1,1,1]]
Output: [[1,0,1],[0,0,0],[1,0,1]]

Example 2:

Input: matrix = [[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
  • -231 <= matrix[i][j] <= 231 - 1

Follow up:

  • A straightforward solution using O(mn) space is probably a bad idea.
  • A simple improvement uses O(m + n) space, but still not the best solution.
  • Could you devise a constant space solution?

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What are the constraints on the dimensions of the matrix ($m$ and $n$), and can the matrix be empty?
  2. Can the matrix contain negative numbers, or are we guaranteed that the elements are non-negative integers?
  3. When we modify the matrix in-place, should we be careful about propagating newly introduced zeros, or should we only target the zeros that originally existed in the matrix?
  4. Is $O(1)$ auxiliary space complexity strictly required, or is using $O(m + n)$ space for tracking rows and columns acceptable as a starting point?
  5. Are there any memory limits or constraints regarding modifying the input matrix references when dealing with very large matrices?

Brute Force Solution

Approach

Imagine looking at a grid filled with numbers and spotting a zero. The brute force strategy involves searching the entire grid for zeros, and whenever one is found, safely marking its entire row and column for erasure without disrupting the rest of the search.

Here's how the algorithm would work step-by-step:

  1. Scan through the entire grid from top to bottom, left to right, looking for any spot that contains the number zero.
  2. Whenever you discover a zero, make a mental note of its exact row and column position.
  3. Go back over the grid and find every position that shares either the same row or the same column as the zero you just discovered.
  4. Change the number in each of those matching positions to a special temporary marker so you know they need to be wiped out, but be careful not to use actual zeros yet or you might get confused during your search.
  5. Continue searching the rest of the grid for any other original zeros, repeating the process of noting their rows and columns.
  6. Once you have checked every single spot in the grid and marked all the necessary rows and columns, go through the grid one final time.
  7. Replace every single temporary marker you placed with a true zero, leaving all other untouched numbers exactly as they were.

Code Implementation

def set_zeroes(matrix):
    row_count = len(matrix)
    column_count = len(matrix[0])
    marker_value = float('inf')

    # We scan the entire matrix first to locate original zeros without false triggers    for row_index in range(row_count):
        for column_index in range(column_count):
            if matrix[row_index][column_index] == 0:
                for target_column in range(column_count):
                    if matrix[row_index][target_column] != 0:
                        matrix[row_index][target_column] = marker_value

                for target_row in range(row_count):
                    if matrix[target_row][column_index] != 0:
                        matrix[target_row][column_index] = marker_value

    # We use a temporary marker to avoid confusing subsequent zero searches in the grid    for row_index in range(row_count):
        for column_index in range(column_count):
            if matrix[row_index][column_index] == marker_value:
                matrix[row_index][column_index] = 0

Big(O) Analysis

Time Complexity
O(R * C) – To analyze the time complexity, let R represent the number of rows and C represent the number of columns in the grid. The initial scan requires visiting every single cell in the R by C matrix to locate the zeros. Subsequently, the marking and final replacement phases also traverse the grid's cells multiple times, doing constant-time checks and updates for each position. Across all phases, the total operations scale proportionally to the product of the dimensions, approximating roughly 3 * (R * C) total operations. Dropping the constant multiplier yields a final time complexity of O(R * C).
Space Complexity
O(1) – The plain English explanation describes using mental notes or temporary markers, but in an optimized in-place solution, we use only a few constant scalar variables to track row and column states without allocating extra data structures. Because no auxiliary arrays, hash maps, or recursion stacks scale with the input dimensions, the extra memory remains constant. If the input matrix contains N total elements, the algorithm requires no additional space dependent on N. Therefore, the auxiliary space complexity simplifies to Big O of 1.

Optimal Solution

Approach

Instead of using extra space to remember which spots need to be wiped out, the optimal approach uses the edges of the grid itself as a memory board. By checking the outer borders first, we can cleverly track our targets without needing any extra materials.

Here's how the algorithm would work step-by-step:

  1. Look at the very top row and the very left column to see if any zeros are hiding there, and remember their status for later.
  2. Walk through the rest of the grid, and whenever you spot a zero, mark its corresponding position on the top edge and the left edge to keep track of it.
  3. Go back through the inner part of the grid and wipe out any cell if its matching marker on the top edge or left edge tells it to.
  4. Finally, use your initial memory from the very first step to decide whether the top row and left column themselves need to be completely wiped out.

Code Implementation

def set_zeroes(matrix_grid):
    if not matrix_grid or not matrix_grid[0]:
        return

    row_count = len(matrix_grid)
    column_count = len(matrix_grid[0])
    top_row_has_zero = False
    left_col_has_zero = False

    for column_index in range(column_count):
        if matrix_grid[0][column_index] == 0:
            top_row_has_zero = True
            break

    for row_index in range(row_count):
        if matrix_grid[row_index][0] == 0:
            left_col_has_zero = True
            break

    # We use edges as markers to avoid extra space complexity.
    for row_index in range(1, row_count):
        for column_index in range(1, column_count):
            if matrix_grid[row_index][column_index] == 0:
                matrix_grid[row_index][0] = 0
                matrix_grid[0][column_index] = 0

    # Inner cells are updated based on markers found on the borders.
    for row_index in range(1, row_count):
        for column_index in range(1, column_count):
            if matrix_grid[row_index][0] == 0 or matrix_grid[0][column_index] == 0:
                matrix_grid[row_index][column_index] = 0

    # The first row and column are updated independently based on initial checks.
    if top_row_has_zero:
        for column_index in range(column_count):
            matrix_grid[0][column_index] = 0

    if left_col_has_zero:
        for row_index in range(row_count):
            matrix_grid[row_index][0] = 0

Big(O) Analysis

Time Complexity
O(m * n) – To analyze the time complexity, let m represent the number of rows and n represent the number of columns in the grid. First, we scan the top row and left column, followed by a double nested loop to inspect all inner cells and set the edge markers. Next, we use those edge markers in another nested loop to update the inner matrix cells, and finally, we conditionally clear the top row and left column. Across all these distinct phases, every single cell in the m by n grid is visited a constant number of times. This results in approximately 4 * (m * n) total operations, which simplifies to O(m * n).
Space Complexity
O(1) – To determine the auxiliary space, we evaluate the memory consumed beyond the input matrix itself. The algorithm uses only a few primitive scalar variables to track the status of the top row and left column, rather than allocating any extra data structures like temporary lists or hash maps. By reusing the first row and first column of the existing grid as markers, the extra memory usage remains completely constant regardless of the matrix dimensions. Therefore, the space complexity simplifies to Big O of 1.

Edge Cases

Empty matrix or matrix with zero rows or columns
How to Handle:
Check for null or empty inputs at the very beginning and return immediately without performing operations.
Matrix of size 1x1 containing either zero or a non-zero value
How to Handle:
The algorithm should bypass row and column marker logic since a single element cannot trigger zeroing of external rows and columns.
Matrix where the top-left element itself is zero
How to Handle:
Use a dedicated boolean flag to track whether the first column should be zeroed independently from the first row marker.
Matrix with all elements already set to zero
How to Handle:
The algorithm naturally processes and maintains all zeros without redundant modifications or infinite loops.
Matrix with no zeros present anywhere
How to Handle:
The initial scan finds no zeros, leaving the matrix completely unmodified as required.
Matrix containing negative numbers and extreme boundary values
How to Handle:
Since zero is the only sentinel trigger, negative numbers are treated as standard non-zero values and do not interfere with the logic.
Very large matrices approaching maximum constraints
How to Handle:
The in-place constant space O(1) approach prevents memory limit exceeded errors by reusing the first row and column as markers.
Zeros located exclusively in the first row or first column
How to Handle:
Separate tracking variables ensure the first row and first column state are preserved correctly before being zeroed out last.
0/257 completed