Algorithm to modify a matrix and set columns and rows to zero

Viewed 5077

This is technically a code challenge. I was asked an interesting question at an interview and am hoping for some insight as the best answer I could come up with was O(2n^2) - n-squared category, but still pretty much brute force.

Let's say you have a matrix that's M by N size ( an array of arrays (int[][]) )

1 2 4 3 1
0 5 3 7 7
5 8 9 2 8
6 7 0 8 9

If a cell contains a Zero, then set that entire row and column to zero.
Making the result:

0 2 0 3 1
0 0 0 0 0 
0 8 0 2 8
0 0 0 0 0 

What is the fastest and/or best way to do this?


My own answer is to iterate the entire array of arrays, keep track of rows and columns to zero out, and then zero them out.

public void zeroOut(int[][] myArray){
    ArrayList<Integer> rowsToZero = new....
    ArrayList<Integer> columnsToZero = new....

    for(int i=0; i<myArray.length; i++){ // record which rows and columns will be zeroed
        for(int j=0; j<myArray[i].length; i++){
            if(myArray[i][j] == 0){
                if(!rowsToZero.contains(i)) rowsToZero.add(i);
                if(!columnsToZero.contains(j)) columnsToZero.add(j);
            }
        }
    }
    for(int row : rows){ // now zero the rows
        myArray[row] = int[myArray.length];
    }

    for(int i=0; i<myArray.length; i++){
        for(int column: columns){ // now zero the columns
            myArray[i][column] = 0;
        }    
    }
}

Is there a better algorithm? Is there a better data-structure to represent this matrix?

5 Answers
Related