David to DSAEnglish • 2 days ago

How do you mark zeroes in an m x n matrix in O(1) space using the first row and column as flag markers?

message-square
0
1
How do you mark zeroes in an m x n matrix in O(1) space using the first row and column as flag markers?
David to DSAEnglish • 2 days ago

Set Matrix Zeroes: $O(1)$ Auxiliary Space via In-Place Flag Markers

The Set Matrix Zeroes problem requires setting an entire row and column to zero whenever a cell contains 0, operating on an $m \times n$ matrix.

Using a secondary $m \times n$ matrix takes $O(m \cdot n)$ space. Using two boolean arrays to track zero rows and columns reduces memory to $O(m + n)$.

To achieve true $O(1)$ auxiliary space, we use the first row and first column of the input matrix itself as our marker arrays. Because the top-left cell matrix[0][0] overlaps both the first row and first column, a single separate boolean variable is used to resolve the conflict.


The Overlap Hazard & Marker Strategy

  • matrix[0][c] = 0 marks that column c must eventually be zeroed.
  • matrix[r][0] = 0 marks that row r must eventually be zeroed.
  • The Collision at (0, 0): Cell matrix[0][0] cannot simultaneously represent both row 0 and column 0 without ambiguity.
  • Resolution:
    • Let matrix[0][0] serve as the flag for row 0.
    • Use an independent boolean flag first_col_zero to track whether column 0 originally contains any zeroes.

Algorithmic Execution Steps

  1. Scan and Mark (Record Zeroes):

    • Inspect column 0: if any cell matrix[r][0] == 0, set first_col_zero = true.
    • Traverse the rest of the matrix (rows 0 to m - 1, columns 1 to n - 1). If matrix[r][c] == 0: $$\text{matrix}[r][0] = 0 \quad (\text{flag row } r)$$ $$\text{matrix}[0][c] = 0 \quad (\text{flag column } c)$$
  2. Update Inner Cells (Bottom-Up or Skip Markers):

    • Iterate over the inner cells from row 1 to m - 1 and column 1 to n - 1.
    • If either its row flag (matrix[r][0] == 0) or column flag (matrix[0][c] == 0) is set, zero out the cell: $$\text{matrix}[r][c] = 0$$ (Crucial: Process inner cells before modifying the first row and column, otherwise overwritten marker flags will erroneously trigger false zeroing across the remaining grid).
  3. Update First Row:

    • If matrix[0][0] == 0, set all elements in row 0 to 0.
  4. Update First Column:

    • If first_col_zero == true, set all elements in column 0 to 0.

Implementation (C++ and Python)

C++ Implementation

#include <vector>

void setZeroes(std::vector<std::vector<int>>& matrix) {
    int m = matrix.size();
    int n = matrix[0].size();
    bool first_col_zero = false;

    // Step 1: Record flags in first row and first column
    for (int r = 0; r < m; ++r) {
        if (matrix[r][0] == 0) {
            first_col_zero = true;
        }
        for (int c = 1; c < n; ++c) {
            if (matrix[r][c] == 0) {
                matrix[r][0] = 0; // Row marker
                matrix[0][c] = 0; // Column marker
            }
        }
    }

    // Step 2: Zero out inner submatrix based on markers
    for (int r = 1; r < m; ++r) {
        for (int c = 1; c < n; ++c) {
            if (matrix[r][0] == 0 || matrix[0][c] == 0) {
                matrix[r][c] = 0;
            }
        }
    }

    // Step 3: Zero out the first row if flagged
    if (matrix[0][0] == 0) {
        for (int c = 0; c < n; ++c) {
            matrix[0][c] = 0;
        }
    }

    // Step 4: Zero out the first column if flagged
    if (first_col_zero) {
        for (int r = 0; r < m; ++r) {
            matrix[r][0] = 0;
        }
    }
}

Python Implementation

def set_zeroes(matrix: list[list[int]]) -> None:
    """
    Modifies matrix in-place to set entire rows and columns to zero.
    Uses O(1) auxiliary space.
    """
    m, n = len(matrix), len(matrix[0])
    first_col_zero = False

    # Step 1: Flag rows and columns using first column and first row
    for r in range(m):
        if matrix[r][0] == 0:
            first_col_zero = True
        for c in range(1, n):
            if matrix[r][c] == 0:
                matrix[r][0] = 0
                matrix[0][c] = 0

    # Step 2: Use markers to fill inner cells (1 to m-1, 1 to n-1)
    for r in range(1, m):
        for c in range(1, n):
            if matrix[r][0] == 0 or matrix[0][c] == 0:
                matrix[r][c] = 0

    # Step 3: Handle the first row
    if matrix[0][0] == 0:
        for c in range(n):
            matrix[0][c] = 0

    # Step 4: Handle the first column
    if first_col_zero:
        for r in range(m):
            matrix[r][0] = 0

Complexity Analysis

Metric Complexity Explanation
Time Complexity $O(m \cdot n)$ Two passes over the matrix of dimension $m \times n$. Every cell is inspected and updated a constant number of times.
Auxiliary Space $O(1)$ No external memory buffers are allocated. Only a single scalar flag (first_col_zero) is used; all other tracking data resides inside existing cell boundaries.

Why Processing Order Matters

If you update row 0 or column 0 before filling the inner cells (matrix[1...m-1][1...n-1]), you will overwrite the marker flags with zeroes prematurely. Once a marker row becomes all zeroes, subsequent passes will interpret those newly placed zeroes as signals to erase every remaining row and column, destroying the entire matrix. Processing the inner grid first prevents cascading corruption.