Clear Rows and Columns Triggered by Original Zeros

Quick Overview

Zero matrix rows and columns triggered by original zero cells, with in-place mutation and a constant-space follow-up.

Clear Rows and Columns Triggered by Original Zeros

Company: Amazon

Role: Software Engineer

Category: Coding & Algorithms

Difficulty: medium

Interview Round: Other

### Problem Modify the integer matrix `matrix` in place. For every cell that was zero in the input, make all cells in that cell's row and column zero. Every other cell keeps its original value. Newly written zeros do not trigger additional rows or columns. Keep the void interface: ```cpp void setZeroes(vector<vector<int>>& matrix); ``` ### Examples ```text Input: matrix = [[2,0,4],[5,6,7]] Matrix after call: [[0,0,0],[5,0,7]] ``` ```text Input: matrix = [[1,2],[0,3],[4,5]] Matrix after call: [[0,2],[0,0],[0,5]] ``` ### Constraints - The input has `m` rows and `n` columns of equal length, with `1 <= m,n <= 200`. - Every entry is between -2147483648 and 2147483647, inclusive. - Change the supplied matrix directly; there is no returned replacement matrix. ### Source follow-up Compare an `O(m*n)` space approach and an `O(m+n)` space improvement, then devise a method using constant extra space.

Overview: Zero matrix rows and columns triggered by original zero cells, with in-place mutation and a constant-space follow-up.

Amazon logo
Amazon
Date not reported
mediumSoftware EngineerOtherCoding & Algorithms
0
0

Problem

Modify the integer matrix matrix in place. For every cell that was zero in the input, make all cells in that cell's row and column zero. Every other cell keeps its original value. Newly written zeros do not trigger additional rows or columns.

Keep the void interface:

void setZeroes(vector<vector<int>>& matrix);

Examples

Input: matrix = [[2,0,4],[5,6,7]]
Matrix after call: [[0,0,0],[5,0,7]]
Input: matrix = [[1,2],[0,3],[4,5]]
Matrix after call: [[0,2],[0,0],[0,5]]

Constraints

  • The input has m rows and n columns of equal length, with 1 <= m,n <= 200 .
  • Every entry is between -2147483648 and 2147483647, inclusive.
  • Change the supplied matrix directly; there is no returned replacement matrix.

Source follow-up

Compare an O(m*n) space approach and an O(m+n) space improvement, then devise a method using constant extra space.