← Google bank

Google · Question 9 · Arrays

Set Matrix Zeroes

ArraysPythoncode⏱ O(m*n)💾 O(1)
Product-based

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. 1Use the first row and column to mark zero presence.
  2. 2Mark zeros found in the inner matrix on the first row/column.
  3. 3Zero out rows and columns based on the markers.
  4. 4Handle 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

Time O(m*n)Space O(1)Loops 8Branches 6Returns 1source · Python
Scroll sideways for wide charts — the view follows the active step.
↻ repeatyes↻ repeat↻ repeatyes↻ repeat↻ repeat↻ repeatyes↻ repeat↻ repeat↻ repeatyesno↻ repeatyesno↻ repeatyesnoSTARTmatrixrows, 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] == 0matrix[i][0] = 0matrix[0][j] = 0for i in range(1,rows)if matrix[i][0] == 0for j in range(1,cols)matrix[i][j] = 0for j in range(1,cols)if matrix[0][j] == 0for i in range(1,rows)matrix[i][j] = 0if row_zerofor j in range(cols)matrix[0][j] = 0if col_zerofor i in range(rows)matrix[i][0] = 0RETURN matrixDEFINE main()import sysdata =sys.stdin.read().split()it = iter(data)m = int(next(it)); n =int(next(it))matrix = [[int(next(it))for _ in range(n)] for _ inrange(m)]print(setZeroes(matrix))if __name__ =="__main__"main()END
  • start / end
  • statement
  • condition
  • loop
  • returns
  • definition
1/34

StartSTART

Interactive control-flow diagram and step-by-step code walkthrough.

Recommended resourcesAffiliate links · may earn us a commission

Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits