Matrices
Set Matrix Zeroes
DESCRIPTION (inspired by 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.
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.
Understanding the Problem
Use the Matrix Itself!
- matrix[i][0] = 0 → "row i needs to be zeroed"
- matrix[0][j] = 0 → "column j needs to be zeroed"
Walkthrough
Step 1: Save first row/column state
Step 2: Mark zeros using first row/column
Step 3: Zero the inner matrix
Step 4: Handle first row/column
Solution
def setZeroes(matrix):rows, cols = len(matrix), len(matrix[0])first_row_zero = any(matrix[0][j] == 0 for j in range(cols))first_col_zero = any(matrix[i][0] == 0 for i in range(rows))for i in range(1, rows):for j in range(1, cols):if matrix[i][j] == 0:matrix[i][0] = 0matrix[0][j] = 0for i in range(1, rows):for j in range(1, cols):if matrix[i][0] == 0 or matrix[0][j] == 0:matrix[i][j] = 0if first_row_zero:for j in range(cols):matrix[0][j] = 0if first_col_zero:for i in range(rows):matrix[i][0] = 0return matrix
Set Matrix Zeroes - O(1) space solution
0 / 15
Test Your Knowledge
Login to take the complexity quiz and track your progress
Complexity Analysis
Time Complexity: O(m × n) We make a constant number of passes through the matrix: once to check first row/column, once to mark, once to zero inner cells, and potentially once each for first row/column.
Space Complexity: O(1) We only use two boolean variables. The first row and column of the matrix itself serve as our markers, requiring no additional space proportional to input size.
Mark as read
Your account is free and you can post anonymously if you choose.