Problem 336996 · medium · Level 03 Linear Management & Searching

Blank Out Rows and Columns

matrix · in-place · marking

Given an m x n integer grid matrix, every cell whose value is 0 "blanks out" its entire row and its entire column: all of those cells must become 0. Perform the change in place and return matrix.

Be careful: a cell that you set to 0 during the process must not itself blank out further rows or columns. Only the zeros present in the input count.

Examples

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

Input:  matrix = [[5, 0, 3, 9], [1, 2, 4, 0], [6, 8, 7, 2]]
Output: [[0, 0, 0, 0], [0, 0, 0, 0], [6, 0, 7, 0]]
Explanation: rows 0 and 1 and columns 1 and 3 are cleared.

Constraints

  • 1 <= m, n <= 200
  • The change must happen in the grid you are given. One test calls grid_after(matrix), which runs your blank_out and then returns matrix itself (not your return value), so the zeros must be in it.
  • Target: O(m * n) time. A first solution may use O(m + n) extra space; the follow-up is O(1).

Goals

  • Record which rows and columns must be cleared before changing anything
  • Use the first row and column of the grid itself as the record to reach O(1) extra space
  • Return the mutated grid
Starting Python…