Skip to main content
← Problem catalogue Understand the pattern. Try it yourself. Review the solution. Practice this pattern →
Medium Matrix High frequency Solution Available Practice Mode

Set Matrix Zeroes LeetCode Solution

Tags: #Array #Matrix

Approach Summary

Use first row and column as markers. Mark zero locations, then zero out rows/columns accordingly.

Practice Mode 2 Progressive Approaches

Solve it yourself before revealing the code

DSA interviews test reasoning from brute force to optimal. Think through the constraints first.

Algorithmic Pattern

Master the Matrix Pattern

View Pattern Guide →

Study the core invariant, step-by-step decision framework, and common interview traps for the Matrix pattern.

Framework: Matrix • Interview Prep: Tested at FAANG • Explore all Matrix problems & invariants →

How to Recognize This Pattern

  • Zero out rows and columns in-place
  • Use first row/col as flags

Complexity Analysis

Time Complexity

O(m × n)

Space Complexity

O(1)

Tags

Array Matrix

Frequently Asked Questions

What is the optimal time and space complexity for Set Matrix Zeroes?
The optimal solution for Set Matrix Zeroes achieves O(m × n) runtime complexity and requires O(1) auxiliary space. Time Complexity is O(M * N) where M is the number of rows and N is the number of columns. We perform two full passes over the matrix cells. Space Complexity is O(1) auxiliary space because state is tracked in-place inside the first row and first column of the input matrix, with only a few primitive variables.
How do I identify that Set Matrix Zeroes requires the Matrix pattern?
In technical interviews, look for key problem signals: Zero out rows and columns in-place; Use first row/col as flags. Recognizing these invariants allows you to bypass naive brute-force exhaustive search in favor of Matrix strategy.
What critical edge cases must be handled in Set Matrix Zeroes?
Essential edge cases to verify include: Single row matrix [[1, 0, 3]] — row becomes all zeros; Single column matrix [[1], [0], [3]] — column becomes all zeros; Matrix[0][0] is originally 0 — correctly zeros out both row 0 and col 0 without corrupting other flags; Matrix with no zeros — remains completely unmodified. Always walk through these scenarios with your interviewer before coding.
Which tech companies frequently ask Set Matrix Zeroes?
Set Matrix Zeroes is a Medium-difficulty question tagged with high recurrence. It is actively asked in technical screening and onsite interview loops at Amazon, Microsoft, Apple.
Buy me a coffee
Daily Practice
0/0