73. Set Matrix Zeroes

Description

Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in-place.

Constraints

Approach

Examples

Input: [ [1, 1, 1], [1, 0, 1], [1, 1, 1] ]

Output: [ [1, 0, 1], [0, 0, 0], [1, 0, 1] ]

Solutions

/**
 * Time complexity : O((M×N)×(M+N)) where M and N are the number of rows and columns 
 *    respectively. Even though this solution avoids using space, but is very 
 *    inefficient since in worst case for every cell we might have to zero out its 
 *    corresponding row and column. Thus for all (M×N) cells zeroing out (M+N) cells.
 * Space complexity : O(1)
 */

class Solution {
    public void setZeroes(int[][] matrix) {
        int row = matrix.length;
        int col = matrix[0].length;
        int MAX = -1000000;
        for(int i = 0; i < row; i++) {
            for(int j = 0; j < col; j++) {
                if(matrix[i][j] == 0) {
                    for(int k = 0; k < row; k++) {
                        if(matrix[k][j] != 0) {
                            matrix[k][j] = MAX;
                        }
                    }
                    for(int k = 0; k < col; k++) {
                        if(matrix[i][k] != 0) {
                            matrix[i][k] = MAX;
                        }
                    }
                }
            }
        }
        for(int i = 0; i < row; i++) {
            for(int j = 0; j < col; j++) {
                if(matrix[i][j] == MAX) {
                    matrix[i][j] = 0;
                }
            }
        }
    }
}

Follow up

  • A straight forward solution using O(mn) space is probably a bad idea.

  • A simple improvement uses O(m + n) space, but still not the best solution.

  • Could you devise a constant space solution?

Last updated

Was this helpful?