Count Zeros in a Row Wise and Column Wise Sorted Matrix

Last Updated : 2 May, 2026

Given a n x n binary matrix mat[][] where each row and column of the matrix is sorted in ascending order, count number of 0s present in it.

Examples: 

Input: mat[][] = [[0,0,0], [0,0,1], [0,1,1]]

blobid2_1777705528

Output: 6
Explanation:  The first, second and third row contains 3, 2 and 1 zeroes respectively.

Input: 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]]
Output: 8
Explanation: The first, second and third row contains 4, 3 and 1 zeroes respectively.

Try It Yourself
redirect icon

[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>
using namespace std;

int countZeros(vector<vector<int>> &mat)
{
    int n = mat.size();
    int count = 0;

    // check every cell
    for (int i = 0; i < n; i++)
    {
        for (int j = 0; j < n; j++)
        {
            if (mat[i][j] == 0)
            {
                count++;
            }
        }
    }

    return count;
}

// Driver Code
int main()
{

    vector<vector<int>> mat = {{0, 0, 0}, {0, 0, 1}, {0, 1, 1}};
    cout << countZeros(mat);

    return 0;
}
C
#include <stdio.h>

int countZeros(int mat[3][3])
{
    int n = 3;
    int count = 0;

    // check every cell
    for (int i = 0; i < n; i++)
    {
        for (int j = 0; j < n; j++)
        {
            if (mat[i][j] == 0)
            {
                count++;
            }
        }
    }

    return count;
}

// Driver Code
int main()
{
    int mat[3][3] = {{0, 0, 0}, {0, 0, 1}, {0, 1, 1}};
    printf("%d", countZeros(mat));

    return 0;
}
Java
public class Main {
    public static int countZeros(int[][] mat) {
        int n = mat.length;
        int count = 0;

        // check every cell
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                if (mat[i][j] == 0) {
                    count++;
                }
            }
        }

        return count;
    }

    public static void main(String[] args) {
        int[][] mat = {{0, 0, 0}, {0, 0, 1}, {0, 1, 1}};
        System.out.println(countZeros(mat));
    }
}
Python
class Solution:
    def countZeros(self, mat):
        n = len(mat)
        count = 0

        for i in range(n):
            for j in range(n):
                if mat[i][j] == 0:
                    count += 1

        return count


# Driver Code
mat = [[0, 0, 0], [0, 0, 1], [0, 1, 1]]

obj = Solution()
print(obj.countZeros(mat))
JavaScript
function countZeros(mat) {
    let n = mat.length;
    let count = 0;

    // check every cell
    for (let i = 0; i < n; i++) {
        for (let j = 0; j < n; j++) {
            if (mat[i][j] === 0) {
                count++;
            }
        }
    }

    return count;
}

// Driver Code
let mat = [[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>
using namespace std;


int countZeros(vector<vector<int>>& mat) {
    int n = mat.size();    
  
    // start from the bottom-left corner
    int row = n - 1, col = 0;
    int count = 0;          

    while (col < n) {
      
        // move up until you find a 0
        while (row >= 0 && mat[row][col]) {
            row--;
        }

        // add the number od zeros
        count += (row + 1);

        // move to the next column
        col++;
    }

    return count;
}

int main() {
    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);

    return 0;
}
C
#include <stdio.h>

int countZeros(int mat[][5], int n) {
    int row = n - 1, col = 0;
    int count = 0;

    while (col < n) {
        while (row >= 0 && mat[row][col] == 1) {
            row--;
        }
        count += (row + 1);
        col++;
    }
    return count;
}

int main() {
    int mat[5][5] = {
        {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}
    };

    printf("%d", countZeros(mat, 5)); 

    return 0;
}
Java
public class GfG {
    public static int countZeros(int[][] mat) {
        int n = mat.length;
        int row = n - 1, col = 0;
        int count = 0;

        while (col < n) {
            while (row >= 0 && mat[row][col]!= 0) {
                row--;
            }
            count += (row + 1);
            col++;
        }
        return count;
    }

    public static void main(String[] args) {
        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}
        };
        System.out.println(countZeros(mat));
    }
}
Python
def countZeros(mat):
    n = len(mat)
    row = n - 1
    col = 0
    count = 0

    while col < n:
        while row >= 0 and mat[row][col]:
            row -= 1
        count += (row + 1)
        col += 1

    return count


if __name__ == "__main__":
    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]
    ]
    print(countZeros(mat))
C#
using System;

public class Program
{
    public static int countZeros(int[][] mat)
    {
        int n = mat.Length;
        int row = n - 1, col = 0;
        int count = 0;

        while (col < n)
        {
            while (row >= 0 && mat[row][col]!= 0)
            {
                row--;
            }
            count += (row + 1);
            col++;
        }
        return count;
    }

    public static void Main()
    {
        int[][] mat = new int[][]
        {
            new int[] {0, 0, 0, 0, 1},
            new int[] {0, 0, 0, 1, 1},
            new int[] {0, 1, 1, 1, 1},
            new int[] {1, 1, 1, 1, 1},
            new int[] {1, 1, 1, 1, 1}
        };
        Console.WriteLine(countZeros(mat));
    }
}
JavaScript
function countZeros(mat) {
    let n = mat.length;
    let row = n - 1, col = 0;
    let count = 0;

    while (col < n) {
        while (row >= 0 && mat[row][col]!== 0) {
            row--;
        }
        count += (row + 1);
        col++;
    }
    return count;
}

let 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]
];
console.log(countZeros(mat));

Output
8
Comment