Skip to content

Latest commit

 

History

History

73

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 

Given an m x n integer matrix matrix, if an element is 0, set its entire row and column to 0's, and return the matrix.

You must do it in place.

 

Example 1:

Input: matrix = [[1,1,1],[1,0,1],[1,1,1]]
Output: [[1,0,1],[0,0,0],[1,0,1]]

Example 2:

Input: matrix = [[0,1,2,0],[3,4,5,2],[1,3,1,5]]
Output: [[0,0,0,0],[0,4,5,0],[0,3,1,0]]

 

Constraints:

  • m == matrix.length
  • n == matrix[0].length
  • 1 <= m, n <= 200
  • -231 <= matrix[i][j] <= 231 - 1

 

Follow up:

  • A straightforward 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?

Companies:
Microsoft, Facebook, Amazon, Qualtrics

Related Topics:
Array, Hash Table, Matrix

Similar Questions:

Solution 1.

// OJ: https://leetcode.com/problems/set-matrix-zeroes/
// Author: github.com/lzl124631x
// Time: O(MN)
// Space: O(M + N)
class Solution {
public:
    void setZeroes(vector<vector<int>>& A) {
        int M = A.size(), N = A[0].size();
        vector<bool> row(M), col(N);
        for (int i = 0; i < M; ++i) {
            for (int j = 0; j < N; ++j) {
                row[i] = row[i] || A[i][j] == 0;
                col[j] = col[j] || A[i][j] == 0;
            }
        }
        for (int i = 0; i < M; ++i) {
            for (int j = 0; j < N; ++j) {
                if (row[i] || col[j]) A[i][j] = 0;
            }
        }
    }
};

Solution 2.

// OJ: https://leetcode.com/problems/set-matrix-zeroes/
// Author: github.com/lzl124631x
// Time: O(MN)
// Space: O(1)
class Solution {
public:
    void setZeroes(vector<vector<int>>& A) {
        bool firstRow = false, firstColumn = false;
        int M = A.size(), N = A[0].size();
        for (int i = 0; i < N && !firstRow; ++i) firstRow = A[0][i] == 0;
        for (int i = 0; i < M && !firstColumn; ++i) firstColumn = A[i][0] == 0;
        for (int i = 1; i < M; ++i) {
            for (int j = 1; j < N; ++j) {
                if (A[i][j] == 0) A[i][0] = A[0][j] = 0;
            }
        }
        for (int i = 1; i < M; ++i) {
            for (int j = 1; j < N; ++j) {
                 if (A[i][0] == 0 || A[0][j] == 0) A[i][j] = 0;
            }
        }
        if (firstRow) {
            for (int i = 0; i < N; ++i) A[0][i] = 0;
        }
        if (firstColumn) {
            for (int i = 0; i < M; ++i) A[i][0] = 0;
        }
    }
};