logoNEURAL COOK
SearchAll PostsTagsNotesAuthor
logoNEURAL COOK

A posts created with Next.js and Tailwind.css

Explore

  • All posts
  • Notes
  • Snippets
  • Tags
  • RSS feed

Connect

instagramtwitterfacebookyoutubelinkedinmailgithub

© 2026 VIKI. All rights reserved.

Built with
Contents
Table Of Contents
2. Add Two Numbers3. Longest Substring Without Repeating Characters5. Longest Palindromic Substring8. String to Integer (atoi)11. Container With Most Water15. 3Sum17. Letter Combinations of a Phone Number19. Remove Nth Node From End of List22. Generate Parentheses33. Search in Rotated Sorted Array34. Find First and Last Position of Element in Sorted Array48. Rotate Image49. Group Anagrams50. Pow(x, n)53. Maximum Subarray54. Spiral Matrix56. Merge Intervals61. Rotate List73. Set Matrix Zeroes74. Search a 2D Matrix75. Sort Colors78. Subsets137. Single Number II138. Copy List with Random Pointer150. Evaluate Reverse Polish Notation151. Reverse Words in a String153. Find Minimum in Rotated Sorted Array155. Min Stack162. Find Peak Element169. Majority Element198. House Robber207. Course Schedule215. Kth Largest Element in an Array227. Basic Calculator II236. Lowest Common Ancestor of a Binary Tree237. Delete Node in a Linked List238. Product of Array Except Self451. Sort Characters By Frequency540. Single Element in a Sorted Array560. Subarray Sum Equals K636. Exclusive Time of Functions875. Koko Eating Bananas1011. Capacity To Ship Packages Within D Days1101. The Earliest Moment When Everyone Become Friends1283. Find the Smallest Divisor Given a Threshold2140. Solving Questions With Brainpower3169. Count Days Without Meetings3481. Apply Substitutions
Code Scratch/leetcode/medium

73. Set Matrix Zeroes

5 min read
On this pageQuestion
QuestionSolutionPatternHow to IdentifyDescriptionThe IntuitionComplexityCodeCaveatsConcepts to Think AboutLogical Follow-up

# Question

Given an M×NM \times NM×N integer matrix, if an element is 000, set its entire row and column to 000. You must perform this operation in-place using O(1)O(1)O(1) extra space.

# Solution

# Pattern

In-Place State Tracking (Marker Arrays) Use the first row and first column of the input matrix itself as memory to store the states of the other rows and columns, avoiding the need for auxiliary arrays.

# How to Identify

  • The problem involves a matrix or grid.
  • A state change in one cell affects the entire row/column.
  • There is a strict O(1)O(1)O(1) space constraint (disallowing standard boolean arrays for tracking).

# Description

Step-by-step explanation:

  1. State Overlap Problem: The cell matrix[0][0] belongs to both the first row and the first column. We need to decouple them. We use matrix[0][0] to track the first row, and a separate boolean variable col0 to track the first column.
  2. Pass 1 (Marking): Iterate through the matrix top-down. If you encounter a 0 at matrix[i][j], you must mark its row and column. You do this by setting matrix[i][0] = 0 and matrix[0][j] = 0. If a 0 is found in the first column (j == 0), set col0 = true.
  3. Pass 2 (Applying): Iterate through the matrix bottom-up, right-to-left (from m-1, n-1 down to 0, 1).
  4. For each cell, check its corresponding markers at matrix[i][0] and matrix[0][j]. If either is 0, set the cell to 0.
  5. Finalizing: After processing the columns 1 through N-1 for a specific row i, check the col0 boolean. If it's true, set matrix[i][0] = 0. By moving bottom-up, we ensure we don't prematurely overwrite our marker values in the first row.

# The Intuition

"Burning the ships." If you find a zero at matrix[i][j], you already know that the entire row i and column j will eventually become zeroes. Therefore, the first element of that row (matrix[i][0]) and the first element of that column (matrix[0][j]) will inevitably be overwritten to zero anyway. Since they are doomed to become zeroes, it costs us absolutely no information to overwrite them immediately and use them as flags (markers) for the rest of the algorithm.

# Complexity

LabelWorstAverage
Time ComplexityO(M×N)O(M \times N)O(M×N)O(M×N)O(M \times N)O(M×N)
Space ComplexityO(1)O(1)O(1)O(1)O(1)O(1)

# Time Complexity

We traverse the M×NM \times NM×N matrix exactly twice (once to mark, once to apply). Operations inside the loops are O(1)O(1)O(1). Thus, time scales linearly with the number of cells.

# Space Complexity

We manipulate the input matrix in-place and allocate only a single primitive boolean variable (col0) and a few loop counters. The memory footprint does not scale with MMM or NNN.

# Code

class Solution {
    public void setZeroes(int[][] matrix) {
        if (matrix == null || matrix.length == 0 || matrix[0].length == 0) return;
        
        int rows = matrix.length;
        int cols = matrix[0].length;
        boolean col0 = false; 
        
        // Pass 1: Mark rows and columns
        for (int i = 0; i < rows; i++) {
            if (matrix[i][0] == 0) col0 = true;
            for (int j = 1; j < cols; j++) {
                if (matrix[i][j] == 0) {
                    matrix[i][0] = 0; 
                    matrix[0][j] = 0; 
                }
            }
        }
        
        // Pass 2: Apply zeroes backward to preserve markers
        for (int i = rows - 1; i >= 0; i--) {
            for (int j = cols - 1; j >= 1; j--) {
                if (matrix[i][0] == 0 || matrix[0][j] == 0) {
                    matrix[i][j] = 0;
                }
            }
            if (col0) matrix[i][0] = 0;
        }
    }
}

# Caveats

  • Immutability Constraints: If the system architecture enforces pure functional programming or prohibits mutating input parameters, an in-place approach is illegal. You would be forced to allocate a new matrix, making the space complexity O(M×N)O(M \times N)O(M×N).
  • Direction Matters: When applying the zeroes in Pass 2, you must iterate from bottom-to-top, right-to-left. Iterating top-to-bottom will immediately zero out matrix[0][0], destroying the marker for the entire first row before you process the other columns.

# Concepts to Think About

  • Overlapping States: The core difficulty of this problem is that row and column zero converge at matrix[0][0]. Decoupling shared states using a single external variable is a common advanced array manipulation technique.
  • Cache Locality: Matrices in Java are arrays of arrays. Accessing them row-by-row (matrix[i][j]) is highly cache-efficient because the data is loaded into the CPU L1/L2 cache sequentially. Accessing column-by-column causes cache misses.
  • Time/Space Tradeoffs: A naive solution allocates an O(M×N)O(M \times N)O(M×N) clone. A better solution allocates two O(M)+O(N)O(M) + O(N)O(M)+O(N) boolean arrays. The optimal solution reuses the input. Understanding this progression is crucial for system design.

# Logical Follow-up

Question: What if the matrix is largely sparse (contains very few zeroes) but its dimensions are massive (e.g., 100,000×100,000100,000 \times 100,000100,000×100,000), and we cannot modify the input matrix? Solution: Using O(M×N)O(M \times N)O(M×N) space for a clone or even O(M+N)O(M+N)O(M+N) space for boolean arrays might exceed memory limits or cause heavy allocations. Instead, we can use two HashSet<Integer> structures to record the distinct indices of the rows and columns that need to be zeroed. The space complexity drops to O(Z)O(Z)O(Z), where ZZZ is the number of zeroes, which is highly efficient for sparse matrices.

Question: What if you need to perform multiple simultaneous state updates on a grid where the previous state determines the next state (e.g., Game of Life)? You cannot just overwrite the cell, because neighboring cells still need to read its original state. Solution: We use bit manipulation. We can store both the current state and the next state within the same 32-bit integer. For example, 00 (was dead, stays dead), 01 (was alive, dies), 10 (was dead, becomes alive), 11 (was alive, stays alive). This allows us to read the 1st bit for the current evaluation, and then shift bits right >> 1 at the end to apply the next state, maintaining strictly O(1)O(1)O(1) space.

←Previous61. Rotate ListNext→74. Search a 2D Matrix

On this page

QuestionSolutionPatternHow to IdentifyDescriptionThe IntuitionComplexityCodeCaveatsConcepts to Think AboutLogical Follow-up