intermediate11 min read·Updated October 9, 2026

Set Matrix Zeroes Explained: In-Place Markers on 3×3 Grid

Master Set Matrix Zeroes (in-place markers) with a full walkthrough of [[1,1,1],[1,0,1],[1,1,1]], a clear mental model, and edge cases.

By Learnisim AI·Published October 9, 2026
LEARNING ARCSetup → Model in the example → Full trace → Twist → Edge cases → Apply
PREREQUISITES
  • 2D arrays
  • Basic iteration
Set Matrix Zeroes In-Place O(1) Space Strategy Phase 1: The Trap 1 1 1 1 0 1 1 1 1 Immediate write causes cascade Contamination error! Phase 2: First Row/Col Flags 0 1 1 0 0 1 1 1 1 Use Row 0 & Col 0 as markers O(1) extra auxiliary space Phase 3: Zeroed 0 0 0 0 0 0 0 0 0 Clean propagation Complete & Correct Algorithm Step-by-Step Execution Protocol 1 Scan & Mark Flags Check if matrix[i][j] == 0. Set row[i] = 0 & col[j] = 0 Avoids extra space allocation 2 Bottom-Up Propagation Iterate inner cells (1 to n-1). If row/col flag is 0, zero cell. Prevents premature corruption 3 Handle First Row/Col Resolve first row & col using independent boolean Flags prevent overlap conflict
Zero [[1,1,1],[1,0,1],[1,1,1]] overview diagram
Why

Why We Need In-Place Markers for Set Matrix Zeroes

Phase 1: The Trap of Immediate Modification

Imagine you are handed the grid from our working example:
Your task is clear: if any cell contains a 0, turn its entire row and column into 0s. If you try to do this naively by scanning row by row, you run into an immediate disaster. The moment you encounter the 0 at row 1, column 1, you overwrite its neighbors or future rows with zeros too early. When your algorithm later reaches a cell that was originally 1, it might read your newly written 0 and mistakenly think that cell was also originally a zero, cascading zero-contamination across the entire grid.
The most naive fix is to allocate a second matrix in memory, read from the original, and write the cleaned output to the copy. That uses extra space. But interviewers and systems engineers demand an in-place solution: you must modify the original matrix using only auxiliary memory. How can you remember which rows and columns need to be zeroed out without creating a separate tracker array?
Why We Need In-Place Markers for Set Matrix Zeroes Preventing cascade contamination without allocating a second matrix Phase 1: The Naive Cascade Trap 1 0* 1 0 0 0 1 0* 1 • Immediate overwrite destroys history Overwriting cells on-the-fly turns neighbor 1s into fake zeroes (0*). Result: Cascade contamination! Alternative: Extra O(M×N) memory copy? Interviewers demand in-place O(1) space. Phase 2: In-Place Markers (Row/Col 0) R0:0 1 1 C0:0 0 1 1 1 1 Flag Strategy 1. Use 1st row & 1st col as trackers. 2. Scan core first, mark margins. 3. Zero inner cells, then margins last. • O(1) Space Magic Store future state in matrix borders without destroying unread past data. Separate col0 flag prevents overlap! Pass 1: Mark headers | Pass 2: Fill body Pass 3: Clean row/col 0 safely.
Why We Need In-Place Markers for Set Matrix Zeroes diagram
Model

The In-Place Marker Model for Set Matrix Zeroes

Phase 2: The Marker Model

When scanning our locked example matrix, we need to remember which rows and columns must become zero without allocating an auxiliary boolean array. The core mental model is to borrow existing storage space inside the matrix itself.
Instead of creating new memory, we designate the very first row and the very first column of as our marker channels. Whenever we discover a zero at coordinates like , we record that fact by writing a zero at the top of that column () and at the front of that row (). Think of these border cells as indicator lights on a dashboard, signaling which entire paths need to be wiped clean later.
However, borrowing the matrix's own borders introduces a direct structural conflict: what happens to the top-left intersection cell ? Both row 0 and column 0 rely on to store their status, causing an overlap where one bit of data tries to serve two distinct flags. To resolve this, we decouple the intersection by keeping a dedicated boolean variable for column 0 (colZero = false), while letting exclusively govern row 0. This split-brain solution allows us to track all 9 elements of our grid using only constant extra space, memory.
Set Matrix Zeroes: The In-Place Marker Model Using matrix borders as indicator lights with a split-brain colZero variable for O(1) space 1. Scan & Spot Zero at (1,1) 1 1 1 1 0 1 1 1 1 Found 0 at center (row 1, col 1) No extra arrays allowed — must borrow matrix borders! Space Complexity: O(1) 2. Mark Borders & colZero 0 1 1 0 0 1 1 1 1 colZero = false (handles [0][0]) Top row & left col act as dashboard indicator lights. Avoids collision at [0][0] intersection! 3. Sweep & Wipe Clean 0 0 0 0 0 0 0 0 0 Entire Row 1 & Col 1 Zeroed! Second pass processes markers from inside out to outer edges. Time: O(M×N) | Space: O(1)
The In-Place Marker Model for Set Matrix Zeroes diagram
Notation

Mathematical Notation and Definitions for Set Matrix Zeroes

Phase 3: Notation & definitions

To formalize our locked working example, we must establish precise mathematical notation for matrix indices, marker flags, and zero-propagation updates.
Let represent an matrix where each element is accessed via zero-based row index and column index . For our working example, and .
We define the set of all zero coordinates found during the scan phase as:
For our working example, scanning yields . Because we cannot use extra space to store , we designate the first row and the first column as marker arrays. However, because belongs to both the first row and the first column, it creates a potential collision. To resolve this, we split the first-column tracking into a separate boolean scalar flag:
Using this notation, the first row acts as column flags ( if column must become zero), and the remaining first-column elements (for ) act as row flags ( if row must become zero). The state transition for any interior cell (where and ) during the marking pass is given by the update rule:
Try this: Given M = [[1,1,1],[1,0,1],[1,1,1]], evaluate and state the values of M[0][0], M[1][0], and col0 after the first scan pass.
Worked example

Step-by-Step Walkthrough of the In-Place Matrix Zeroing Algorithm

Phase 4: Worked Example

Let us trace our locked example. Our goal is to transform in-place so that any row or column containing a zero becomes entirely zero, without allocating an extra matrix.

Given

A integer matrix , with a single zero located at coordinate (using 0-based indexing):

Step 1: Scan and Set First Row/Column Markers

We inspect all elements outside the first row and column. We discover . This forces us to mark the corresponding row flag and column flag.
- Since is in row 1 and column 1, we set our marker storage: (marking row 1) and (marking column 1).
- Note that we also check if the first row or first column independently contain any zeros. In this specific , neither nor contain a zero initially, so our separate boolean flags row0_has_zero and col0_has_zero remain false.
•Intermediate marker state after scanning:

Step 2: Zero Out Inner Cells Using Markers

Now, we iterate through the submatrix from row 1 to 2 and column 1 to 2. For each cell , if or , we set .
- At , , so becomes 0.
- At , , so becomes 0.
- At , neither marker is 0, so it remains 1.
•Intermediate matrix state:

Step 3: Zero Out First Row and Column Based on Flags

Finally, we process the first row and first column using our saved boolean flags (row0_has_zero and col0_has_zero).
- Since row0_has_zero is false, the first row retains its values except where markers dictated changes.
- Since col0_has_zero is false, the first column retains its values.

Result

The final transformed matrix matches our expected output:
Try this: Start from A = [[1,1,1], [1,0,1], [1,1,1]]. If we add a new zero at A[0][2], what value does A[0][1] hold after Step 1 marker assignment?
Phase 4: In-Place Matrix Zeroing Walkthrough Scan non-first cells, set row/col 0 markers, then propagate zero updates Step 1: Scan & Mark 1 1 1 0 0 1 1 1 1 Found 0 at matrix[1][1] Set row marker: matrix[1][0] = 0 Set col marker: matrix[0][1] = 0 row0haszero / col0haszero = false Step 2: Submatrix Zeroing 1 0 Col Mark 1 0 Row 0 0 1 1 1 Iterate Submatrix (1..2, 1..2) If row/col marker is 0, set cell to 0 Cell (1,2) and (2,2) become 0 Inner cells updated safely Step 3: First Row/Col 1 0 1 0 0 0 1 0 1 Process Flags Check row0haszero Check col0haszero Here: both false, so first row/col zeroed via markers!
Step-by-Step Walkthrough of the In-Place Matrix Zeroing Algorithm diagram
Practice

Practice Trace of In-Place Matrix Zeroes

Phase 5: Practice

It is time to test your mental model against a tricky edge case. Building on our walkthrough, suppose we have a matrix where the zero sits directly on the border:
Remember our core rules: we cannot use an auxiliary array, and we must handle the first row and column flags carefully so they do not overwrite state prematurely. Work through the first pass (flag detection) and the second pass (internal matrix zeroing) for this specific input.

The Exercise

Given the matrix above, determine the exact state of the boolean flags (isFirstRowZero and isFirstColZero) and the resulting matrix state after the internal cells (from row 1 to 2, col 1 to 2) are updated, but before you clean up the first row and column.
Write down or mentally trace:
1. The values of isFirstRowZero and isFirstColZero after inspecting the first row and column.
2. The state of the interior sub-matrix after using cells (0, 1) and (1, 0) as markers.
3.The final output matrix after the final cleanup step.
Apply

Transferring In-Place Markers to Higher-Dimensional Grid Problems

Phase 6: Applying the Marker Pattern Beyond 2D Matrices

The fundamental lesson of our working example on matrices is that excess state can often be folded back into the primary data structure without creating auxiliary memory structures. When we encountered a zero at , we did not allocate a separate boolean[] array; we repurposed the existing boundary row and column as storage flags. This principle of space compression via metadata co-location is a powerful architectural pattern across numerical computing and systems engineering.
Consider a higher-dimensional analogue: a 3D tensor of shape where encountering a zero requires zeroing out its entire plane in three orthogonal directions (, , ). Just as a 2D matrix needs dedicated boolean flags for its first row and first column, a 3D tensor requires dedicated 2D bounding planes to act as our storage markers. By reserving the slice where index equals zero along each dimension to record whether any zero exists in that respective slice, we maintain the strict auxiliary space constraint.
Another powerful transfer is in streaming stream-processing algorithms, where updating state in-place avoids allocation overhead in high-throughput loops. Recognizing that input structures often contain idle or unused bits (like sign bits in fixed-point representations or padding bytes in network packets) allows engineers to piggyback control flags onto raw data payloads, echoing our use of matrix[0][j] as a boolean indicator.
As you tackle neighboring grid problems, always ask: Where is the scratchpad memory hiding in plain sight? Often, the input itself has a designated border or canonical region that can double as a tracking register once its original contents are safely summarized.

FAQ

How does the algorithm handle the [[1,1,1],[1,0,1],[1,1,1]] example?
It uses the first row and column as markers. Since the zero is at (1,1), it marks row 1 and column 1 as zero, resulting in [[1,0,1],[0,0,0],[1,0,1]].
Why use in-place markers instead of a separate boolean array?
Using in-place markers stored inside the matrix reduces the extra space complexity from O(M × N) or O(M + N) down to O(1).
What is the flag split edge case in this problem?
The flag split occurs when a zero already exists in the first row or first column, requiring separate boolean variables to prevent accidental overwrites.
What are the time and space complexities of the in-place approach?
The time complexity is O(M × N) to scan and update the matrix, and the space complexity is O(1) auxiliary space.

Keep learning