Skip to main content
Back to problems
Leetcode
Medium
Arrays
Matrices
Google
Set Matrix Zeroes

Modify a matrix in place so that if any cell is 0, its entire row and column become 0.

Acceptance 100%
Problem Statement

Given an m×nm \times n matrix, update it in place using the following rule: whenever a cell contains 0, every element in that cell’s row and every element in that cell’s column must also be set to 0.

The update should be based on the original positions of the zeroes, not on zeroes created during the process.

Input Format

  • A 2D integer matrix matrix with m rows and n columns.
  • Each cell contains an integer value.

Output Format

  • Modify matrix in place.
  • Return nothing in languages where in-place mutation is expected, or the updated matrix if your environment requires a return value.

Constraints

  • 1 <= m, n
  • The matrix fits in memory.
  • Aim for O(1)O(1) extra space if possible.
  • The update must use the zero positions from the original matrix state.
Examples
Sample cases returned by the problem API.

Example 1

Input

matrix = [[1,1,1],[1,0,1],[1,1,1]]

Output

[[1,1,1],[0,0,0],[1,1,1]]

Explanation

The middle cell is zero, so its entire row and column become zero.

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]]

Explanation

The first row and the first and last columns contain a zero in the original matrix, so those rows and columns are cleared.

Premium problem context

Unlock deeper context for this problem

Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.

Guided hints
Editorial and discussion links
Concept map and variants
Sign in to unlock
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.