# My brief solution using O(m + n) space. Can someone not use extra spaces?

• ``````public void setZeroes(int[][] matrix) {
int m = matrix.length;
int n = matrix[0].length;

boolean[] row = new boolean[m];
boolean[] col = new boolean[n];

for(int i = 0; i < m; i++){
for(int j = 0; j < n; j++){
if(matrix[i][j] == 0){
row[i] = true;
col[j] = true;
}
}
}

for(int i = 0; i < row.length; i++){
if(row[i] == true){
for(int j = 0; j < n; j++){
matrix[i][j] = 0;
}
}
}

for(int i = 0; i < col.length; i++){
if(col[i] == true){
for(int j = 0; j < m; j++){
matrix[j][i] = 0;
}
}
}
}``````

• I think the solution is obvious: use the first row & first column to mark if elements in that row/column should be 0.

``````public class Solution {
public void setZeroes(int[][] matrix) {

boolean firstRowZero = false;
boolean firstColZero = false;

for(int i =0; i<matrix.length; i++)
if(matrix[i][0] == 0) {
firstColZero = true;
break;
}

for(int i =0; i<matrix[0].length; i++)
if(matrix[0][i] == 0) {
firstRowZero = true;
break;
}

for(int i = 1; i<matrix.length; i++){
for(int j = 1; j<matrix[0].length; j++){
if(matrix[i][j] == 0){
matrix[i][0] = 0;
matrix[0][j] = 0;
}
}
}

for(int i=1; i<matrix.length; i++){
if(matrix[i][0] == 0)
for(int j=1; j<matrix[0].length; j++){
matrix[i][j] = 0;
}
}
for(int i=1; i<matrix[0].length; i++){
if(matrix[0][i] == 0)
for(int j=1; j<matrix.length; j++){
matrix[j][i] = 0;
}
}

if (firstRowZero)
for(int i =0; i<matrix[0].length; i++)
matrix[0][i] = 0;
if (firstColZero)
for(int i=0; i<matrix.length; i++)
matrix[i][0] = 0;
}
}``````

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.