Home › Company-wise questions › Google › Set Matrix Zeroes ← Google bank
Google · Question 9 · Arrays
Set Matrix Zeroes Arrays Python code ⏱ O(m*n) 💾 O(1)
Product-based Published and maintained by DSA-topics · Last updated 30 November 2026 · Report an error
About this bank These are classic technical-interview concepts compiled from publicly circulated company-wise question sets, rewritten with original explanations and compiler-ready solutions for educational practice; inclusion does not imply endorsement by the company. Spotted an error? Tell us .
Problem Given a matrix, if an element is 0, set its entire row and column to 0.
Approach Use first row and column as markers to track zero rows/columns.
Time O(m*n)Space O(1)
How it works 1 Use the first row and column to mark zero presence. 2 Mark zeros found in the inner matrix on the first row/column. 3 Zero out rows and columns based on the markers. 4 Handle the first row and column separately. Sample input / output Input:
3 3
1 1 1
1 0 1
1 1 1
Output:
[[1, 0, 1], [0, 0, 0], [1, 0, 1]] Constraints m == matrix.length; n == matrix[i].length; 1 <= m, n <= 200; -2^31 <= matrix[i][j] < 2^31.
Solution — read it, then walk it Flowchart Pseudocode
Time O(m*n)Space O(1)Loops 8Branches 6Returns 1source · Python
Scroll sideways for wide charts — the view follows the active step. ⤢ Expand
↻ repeat yes ↻ repeat ↻ repeat yes ↻ repeat ↻ repeat ↻ repeat yes ↻ repeat ↻ repeat ↻ repeat yes no ↻ repeat yes no ↻ repeat yes no START matrix rows, cols = len(matrix), len(matrix[0]) row_zero = any(matrix[0][j] == 0 for j in range(cols)) 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] = 0 matrix[0][j] = 0 for i in range(1, rows) if matrix[i][0] == 0 for j in range(1, cols) matrix[i][j] = 0 for j in range(1, cols) if matrix[0][j] == 0 for i in range(1, rows) matrix[i][j] = 0 if row_zero for j in range(cols) matrix[0][j] = 0 if col_zero for i in range(rows) matrix[i][0] = 0 RETURN matrix DEFINE main() import sys data = sys.stdin.read().split() it = iter(data) m = int(next(it)); n = int(next(it)) matrix = [[int(next(it)) for _ in range(n)] for _ in range(m)] print(setZeroes(matrix)) if __name__ == "__main__" main() END start / end statement condition loop returns definition← Q8 · Maximum Subarray (Kadane’s Algorithm) Q10 · Rotate Array → Solution code Core logic highlighted in green
Language Pythonsource Java C++ C Core logic Full code Copy
Recommended resources Affiliate links · may earn us a commission
Classic DSA interview books The reference books interviewers themselves learned from — great next to the visualizers. See the books → Structured coding courses Video courses that pair well with visual practice — pick one language and go deep. Browse courses → Cloud hosting for side projects Ship the portfolio project that gets you hired — free credits for new accounts. Claim credits →