Search⌘ K
AI Features

Set Matrix Zeroes

Discover how to identify zero elements in a matrix and update the corresponding rows and columns directly without extra space. This lesson helps you understand efficient in-place matrix modification techniques crucial for coding interviews focusing on matrix operations.

Statement

Given a matrix, mat, if any element within the matrix is zero, set that row and column to zero. The performed operations should be in place, i.e., the given matrix is modified directly without allocating another matrix.

Constraints:

  • 11 \le mat.row, mat.col 20\le 20
  • 231-2^{31} \le mat[i][j] 2311\le 2^{31} - 1

Examples

Understand the problem

Let’s take a moment to make sure you’ve correctly understood the problem. The quiz below helps you check if you’re are solving the correct problem:

Set Matrix Zeros

1.

What is the correct output if the following matrix is given as input?

matrix=[123456709]matrix = \begin{bmatrix}1 & 2 & 3 \\4 & 5 & 6 \\ 7 & 0 & 9 \end{bmatrix}

A.

matrix=[020406000]matrix = \begin{bmatrix}0 & 2 & 0 \\4 & 0 & 6 \\ 0 & 0 & 0 \end{bmatrix}

B.

matrix=[103406000]matrix = \begin{bmatrix}1 & 0 & 3 \\4 & 0 & 6 \\ 0 & 0 & 0 \end{bmatrix}

C.

matrix=[103406709]matrix = \begin{bmatrix}1 & 0 & 3 \\4 & 0 & 6 \\ 7 & 0 & 9 \end{bmatrix}

D.

matrix=[123456000]matrix = \begin{bmatrix}1 & 2 & 3 \\4 & 5 & 6 \\ 0 & 0 & 0 \end{bmatrix}


1 / 3

Figure it out!

We have a game for you to play. Rearrange the logical building blocks to develop a clearer understanding of how to solve this problem.

Sequence - Vertical
Drag and drop the cards to rearrange them in the correct sequence.

1
2
3
4
5

Try it yourself

Implement your solution in the following coding playground.

C++
usercode > SetMatrixZeros.cpp
#include <iostream>
#include <vector>
#include <queue>
vector<vector<int>> SetMatrixZeros(vector<vector<int>>& mat)
{
// Replace this placeholder return statement with your code
return mat;
}
Set Matrix Zeroes