[Naive Approach] Traverse Entire Matrix - O(n²) Time and O(1) Space
The Idea is to traverse every element of the matrix and count the number of zeros, checks all cells.
C++
#include<iostream>usingnamespacestd;intcountZeros(vector<vector<int>>&mat){intn=mat.size();intcount=0;// check every cellfor(inti=0;i<n;i++){for(intj=0;j<n;j++){if(mat[i][j]==0){count++;}}}returncount;}// Driver Codeintmain(){vector<vector<int>>mat={{0,0,0},{0,0,1},{0,1,1}};cout<<countZeros(mat);return0;}
C
#include<stdio.h>intcountZeros(intmat[3][3]){intn=3;intcount=0;// check every cellfor(inti=0;i<n;i++){for(intj=0;j<n;j++){if(mat[i][j]==0){count++;}}}returncount;}// Driver Codeintmain(){intmat[3][3]={{0,0,0},{0,0,1},{0,1,1}};printf("%d",countZeros(mat));return0;}
Java
publicclassMain{publicstaticintcountZeros(int[][]mat){intn=mat.length;intcount=0;// check every cellfor(inti=0;i<n;i++){for(intj=0;j<n;j++){if(mat[i][j]==0){count++;}}}returncount;}publicstaticvoidmain(String[]args){int[][]mat={{0,0,0},{0,0,1},{0,1,1}};System.out.println(countZeros(mat));}}
functioncountZeros(mat){letn=mat.length;letcount=0;// check every cellfor(leti=0;i<n;i++){for(letj=0;j<n;j++){if(mat[i][j]===0){count++;}}}returncount;}// Driver Codeletmat=[[0,0,0],[0,0,1],[0,1,1]];console.log(countZeros(mat));
Output
6
[Expected Approach] - Traverse Column-wise - O(n) Time and O(1) Space
Since the matrix is sorted row-wise and column-wise, we can use its order to avoid checking every cell.
Start from the bottom-left corner.
If the current element is not zero, move upward because any zeros, if present, must be above.
Once a zero is found, all the elements above it in that column will also be zero due to sorting, so we can count them together and then move right to the next column.
By always moving only up or right and never revisiting cells, we efficiently count zeros using the matrix’s sorted structure.
C++
#include<iostream>#include<vector>usingnamespacestd;intcountZeros(vector<vector<int>>&mat){intn=mat.size();// start from the bottom-left cornerintrow=n-1,col=0;intcount=0;while(col<n){// move up until you find a 0while(row>=0&&mat[row][col]){row--;}// add the number od zeroscount+=(row+1);// move to the next columncol++;}returncount;}intmain(){vector<vector<int>>mat={{0,0,0,0,1},{0,0,0,1,1},{0,1,1,1,1},{1,1,1,1,1},{1,1,1,1,1}};cout<<countZeros(mat);return0;}