11 · Matrices & Simulation

#73 Set Matrix Zeroes

Mediumsolve on LeetCode ↗

frequently reported atWalmartBloombergMicrosoftMetaAmazonApple

the problem

In plain words

You are given an m × n matrix of integers. For every cell that holds 0 in the original matrix, turn its entire row and its entire column into 0s. Change the matrix in place. Bonus: use only O(1) extra memory.

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

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

The 0 in the middle wipes row 1 and column 1.

in matrix = [[0,1,2,0],[3,4,5,2],[1,3,1,5]]

out [[0,0,0,0],[0,4,5,0],[0,3,1,0]]

The two zeros in row 0 wipe row 0, column 0 and column 3.

  • 1 ≤ m, n ≤ 200
  • −2³¹ ≤ matrix[i][j] ≤ 2³¹ − 1

your turn

Try it before you peek

Read the examples, say the brute force out loud, then write code: here or on LeetCode ↗. Stuck for 20 minutes? Open one hint at a time.

Solve it in the browser

LeetCode-style: complete the class. Compiled by the real javac (Java 17) and judged right here — nothing is sent anywhere.

    Solutions are hidden so you can try first. Even 20 minutes of real effort makes the answer stick far better than reading it.

    Marking the problem solved, or opening every hint, also shows it.

    practise next

    Similar problems

    1. #289
      Game of Life
      Mediumin Matrices
    2. #41
      First Missing Positive
      Hardin Arrays & Strings
    3. #48
      Rotate Image
      Mediumin Matrices