Arrays and Hashing Walking a matrix

85. Set Matrix Zeroes

Medium

You are given a grid of integers matrix with m rows and n columns. For every cell that holds 0, set every cell in that cell's row and every cell in that cell's column to 0.

Only the zeros of the grid as it is given count. A cell that becomes 0 because of this rule does not clear its own row and column.

Change matrix itself and return it.

Example 1

470231580691
matrix
000001080000
output

Input: matrix = [[4, 7, 0, 2], [3, 1, 5, 8], [0, 6, 9, 1]]

Output: [[0,0,0,0],[0,1,0,8],[0,0,0,0]]

Explanation: The zeros are at row 0, column 2 and at row 2, column 0. So rows 0 and 2 and columns 0 and 2 become 0. Only 1 and 8 in row 1 are in neither, and they stay.

Example 2

012345
matrix
000045
output

Input: matrix = [[0, 1, 2], [3, 4, 5]]

Output: [[0,0,0],[0,4,5]]

Explanation: The only zero is in the top-left corner, so row 0 and column 0 become 0. The 4 and the 5 are in neither.

Example 3

-110⁹7−10⁹
matrix
-110⁹7−10⁹
output

Input: matrix = [[-1, 1000000000], [7, -1000000000]]

Output: [[-1,1000000000],[7,-1000000000]]

Explanation: The grid holds no zero, so nothing changes. Negative numbers are not zeros.

Check your understanding

Work out the answer for this input before you write any code.

matrix = [[5, 0, 7], [1, 2, 3]]

Constraints

  • m == matrix.length, n == matrix[i].length
  • 1 ≤ m, n ≤ 300
  • -109 ≤ matrix[i][j] ≤ 109

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.