← Deloitte bank

Deloitte · Question 32

Set Matrix Zeroes

Javacode⏱ O(mn)💾 O(1)
Service-based

Problem

If an element is 0, set its entire row and column to 0.

Approach

Use the first row/col as markers to achieve O(1) extra space.

Time O(mn)Space O(1)

How it works

  1. 1Mark zero rows/columns on the first row and column.
  2. 2Zero inner cells from the markers, sweeping bottom-up.

Sample input / output

Input:
matrix = [[1, 1, 1], [1, 0, 1], [1, 1, 1]]
Output:
[[1, 0, 1], [0, 0, 0], [1, 0, 1]]

Constraints

1 <= m, n <= 200; O(1) extra space.

Solution — read it, then walk it

Time O(mn)Space O(1)Loops 4Branches 4source · Java
Scroll sideways for wide charts — the view follows the active step.
↻ repeatyes↻ repeat↻ repeat↻ repeat↻ repeatSTARTimport java.util.*DEFINE class MainDEFINE static voidsetZeroes(int[][] matrix)DEFINE m = matrix.length, n= matrix[0].lengthDEFINE firstCol = falsefor (int i = 0; i < m;i++)if (matrix[i][0] == 0)firstCol = truefor (int j = 1; j < n;j++)if (matrix[i][j] == 0)matrix[i][0] = 0matrix[0][j] = 0for (int i = m - 1; i>= 0; i--)for (int j = n - 1; j>= 1; j--)if (matrix[i][0] == 0|| matrix[0][j] == 0)matrix[i][j] = 0if (firstCol)matrix[i][0] = 0DEFINE static voidmain(String[] args)DEFINE [][] m = {{1, 1, 1},{1, 0, 1}, {1, 1, 1}}setZeroes(m)System.out.println(Arrays.deepToString(m))END
  • start / end
  • statement
  • condition
  • loop
  • returns
  • definition
1/20

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