Set Matrix Zeroes
DESCRIPTION (credit Leetcode.com)
Write a function to modify an m x n integer matrix matrix directly, such that if any element in the matrix is 0, its entire corresponding row and column are set to 0. This transformation should be done in place, without using any additional data structures for storage.
EXAMPLES
Input:
matrix = [ [0,2,3], [4,5,6], [7,8,9] ]
Output:
[ [0,0,0], [0,5,6], [0,8,9] ]
Explanation: Since the element at the first row and first column is 0, set all elements in the first row and first column to 0.
Solution
def setZeroes(matrix):rows, cols = len(matrix), len(matrix[0])zero_rows, zero_cols = set(), set()for i in range(rows):for j in range(cols):if matrix[i][j] == 0:zero_rows.add(i)zero_cols.add(j)for row in zero_rows:for col in range(cols):matrix[row][col] = 0for col in zero_cols:for row in range(rows):matrix[row][col] = 0return matrix
Explanation
This solution solves the problem in three steps:
Step 1: Mark the rows and columns to be zeroed
The first step is to iterate over each cell in the matrix, and find the indexes of the rows and columns that need to be zeroed. We can use store those indexes in two sets rows and cols - each time we find a zero in the matrix, we add the row and column indexes to the respective sets.
def setZeroes(matrix):rows, cols = len(matrix), len(matrix[0])zero_rows, zero_cols = set(), set()for i in range(rows):for j in range(cols):if matrix[i][j] == 0:zero_rows.add(i)zero_cols.add(j)for row in zero_rows:for col in range(cols):matrix[row][col] = 0for col in zero_cols:for row in range(rows):matrix[row][col] = 0return matrix
Step 2: Zero the rows
The second step is to zero the rows. We iterate through the rows in the zero_rows set, and set all the elements in that row to zero by iterating through each column in the matrix, and setting those cells to zero.
def setZeroes(matrix):rows, cols = len(matrix), len(matrix[0])zero_rows, zero_cols = set(), set()for i in range(rows):for j in range(cols):if matrix[i][j] == 0:zero_rows.add(i)zero_cols.add(j)for row in zero_rows:for col in range(cols):matrix[row][col] = 0for col in zero_cols:for row in range(rows):matrix[row][col] = 0return matrix
Step 3: Zero the columns
The final step is to zero the columns. We iterate through the columns in the zero_cols set, and set all the elements in that column to zero by iterating through each row in the matrix, and setting those cells to zero.
def setZeroes(matrix):rows, cols = len(matrix), len(matrix[0])zero_rows, zero_cols = set(), set()for i in range(rows):for j in range(cols):if matrix[i][j] == 0:zero_rows.add(i)zero_cols.add(j)for row in zero_rows:for col in range(cols):matrix[row][col] = 0for col in zero_cols:for row in range(rows):matrix[row][col] = 0return matrix
Complexity Analysis
- Time complexity: O(m * n): We iterate through the entire matrix once.
- Space complexity: O(1): We use only a constant amount of space.
Loading comments...