← Accenture bank

Accenture · Question 10 · Arrays

Set Matrix Zeroes

ArraysC++code⏱ O(m×n)💾 O(1)
Service-based

Problem

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

Approach

Use first row and column as markers.

Time O(m×n)Space O(1)

How it works

  1. 1Mark zero rows/columns on the first row and column.
  2. 2Zero the inner cells from the markers.
  3. 3Fix the first row and column last.

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(m×n)Space O(1)Loops 10Branches 8Returns 1source · C++
Scroll sideways for wide charts — the view follows the active step.
↻ repeat↻ repeat↻ repeatyes↻ repeat↻ repeat↻ repeatyes↻ repeat↻ repeatyesnoyesno↻ repeat↻ repeatSTARTinclude <iostream>include <vector>using namespace stdDEFINEsetZeroes(vector<vector<int>>&matrix)bool firstRowZero = false,firstColZero = falseDEFINE rows =matrix.size(), cols =matrix[0].size()for (int r = 0; r <rows; ++r)if (matrix[r][0] == 0)firstColZero = truefor (int c = 0; c <cols; ++c)if (matrix[0][c] == 0)firstRowZero = truefor (int r = 1; r <rows; ++r)for (int c = 1; c <cols; ++c)if (matrix[r][c] == 0)matrix[r][0] = 0matrix[0][c] = 0for (int r = 1; r <rows; ++r)for (int c = 1; c <cols; ++c)if (matrix[r][0] == 0|| matrix[0][c] == 0)matrix[r][c] = 0if (firstColZero)for (int r = 0; r <rows; ++r)matrix[r][0] = 0if (firstRowZero)for (int c = 0; c <cols; ++c)matrix[0][c] = 0DEFINE main()vector<vector<int>> matrix= {{1, 1, 1}, {1, 0, 1},{1, 1, 1}}setZeroes(matrix)cout << "["for (size_t i = 0; i <matrix.size(); ++i)if (i) cout << ", "cout << "["for (size_t j = 0; j <matrix[i].size(); ++j)if (j) cout << ", "cout << matrix[i][j]cout << "]"cout << "]" << endlRETURN 0END
  • start / end
  • statement
  • condition
  • loop
  • returns
  • definition
1/37

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