leeway00 / CodingTestPractice

0 stars 0 forks source link

Set Matrix Zero #5

Open leeway00 opened 2 years ago

leeway00 commented 2 years ago
    def setZeroes(self, matrix: List[List[int]]) -> None:
        """
        Do not return anything, modify matrix in-place instead.
        """
        should_set_row = [False for _ in matrix]
        should_set_col = [False for _ in matrix[0]]

        for i in range(len(matrix)):
            for j in range(len(matrix[0])):
                if matrix[i][j] == 0:
                    should_set_row[i] = True
                    should_set_col[j] = True

        for i, should_set in enumerate(should_set_row):
            if should_set:
                matrix[i] = [0 for _ in matrix[0]]

        for j, should_set in enumerate(should_set_col):
            if should_set:
                for i in range(len(matrix)):
                    matrix[i][j] = 0
leeway00 commented 2 years ago

O(1) space

    def setZeroes(self, matrix: List[List[int]]) -> None:
        """
        Do not return anything, modify matrix in-place instead.
        """
        N = len(matrix)
        M = len(matrix[0])

        first = 0 if 0 in matrix[0] else matrix[0][0]

        n, m = 1,0
        while n < N:
            if matrix[n][m] == 0:
                matrix[0][m] = 0
                matrix[n][0] = 0
            m+=1
            if m == M:
                m=0
                n+=1

        for n, row in enumerate(matrix[1:],1):
            if row[0] == 0:
                matrix[n] = [0]*M
            else:
                for m, val in enumerate(matrix[0]):
                    if val == 0:
                        matrix[n][m]=0
        if first == 0:
            matrix[0] = [0]*M