[LeetCode] 73. Set Matrix Zeroes

Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place.
Follow up:
Did you use extra space?
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?

Thought process:
Iterate through the matrix. If matrix[i][j] == 0, set matrix[0][j] and matrix[i][0] to 0. After iterating through the matrix, iterate through the first row and first column and set the corresponding rows and columns to 0.
Note that the first row and first column could have 0 originally. Go through them and mark if they have 0 before iterating through the matrix.

Solution:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
class Solution {
    public void setZeroes(int[][] matrix) {
        int m = matrix.length;
        if (m == 0) {
            return;
        }
        int n = matrix[0].length;
        
        boolean firstRowHas0 = false;
        boolean firstColHas0 = false;
        
        for (int i = 0; i < m; i++) {
            if (matrix[i][0] == 0) {
                firstColHas0 = true;
                break;
            }
        }
        for (int i = 0; i < n; i++) {
            if (matrix[0][i] == 0) {
                firstRowHas0 = true;
                break;
            }
        }
        
        for (int i = 1; i < m; i++) {
            for (int j = 1; j < n; j++) {
                if (matrix[i][j] == 0) {
                    matrix[i][0] = 0;
                    matrix[0][j] = 0;
                }
            }
        }
        
        for (int i = 1; i < m; i++) {
            if (matrix[i][0] == 0) {
                nullifyRow(matrix, i, 1);
            }
        }
        for (int i = 1; i < n; i++) {
            if (matrix[0][i] == 0) {
                nullifyCol(matrix, i, 1);
            }
        }
        if (firstRowHas0) {
            nullifyRow(matrix, 0, 0);
        }
        if (firstColHas0) {
            nullifyCol(matrix, 0, 0);
        }
    }
    
    private void nullifyRow(int[][] matrix, int row, int start) {
        for (int i = start; i < matrix[0].length; i++) {
            matrix[row][i] = 0;
        }
    }
    
    private void nullifyCol(int[][] matrix, int col, int start) {
        for (int i = start; i < matrix.length; i++) {
            matrix[i][col] = 0;
        }
    }
}

Time complexity: O(mn).
Space complexity: O(1).

Comments

Popular posts from this blog

[LeetCode] 714. Best Time to Buy and Sell Stock with Transaction Fee

[LeetCode] 269. Alien Dictionary

[LeetCode] 631. Design Excel Sum Formula