Sunday, February 8, 2026
HomeLanguagesJavaJava Program to Check if a given matrix is sparse or not

Java Program to Check if a given matrix is sparse or not

A matrix is a two-dimensional data object having m rows and n columns, therefore a total of m*n values. If most of the values of a matrix are 0 then we say that the matrix is sparse. 
Consider a definition of Sparse where a matrix is considered sparse if the number of 0s is more than half of the elements in the matrix,

Examples: 

Input : 1 0 3
        0 0 4
        6 0 0
Output : Yes
There are 5 zeros. This count
is more than half of matrix
size.

Input : 1 2 3
        0 7 8
        5 0 7 
Output: No 

To check whether a matrix is a sparse matrix, we only need to check the total number of elements that are equal to zero. If this count is more than (m * n)/2, we return true. 

Java




// Java code to check
// if a matrix is
// sparse.
 
import java.io.*;
 
class GFG {
     
    static int MAX = 100;
      
    static boolean isSparse(int array[][], int m, int n)
    {
        int counter = 0;
      
        // Count number of zeros in the matrix
        for (int i = 0; i < m; ++i)
            for (int j = 0; j < n; ++j)
                if (array[i][j] == 0)
                    ++counter;
      
        return (counter > ((m * n) / 2));
    }
      
    // Driver Function
    public static void main(String args[])
    {
        int array[][] = { { 1, 0, 3 },
                            { 0, 0, 4 },
                            { 6, 0, 0 } };
      
        int m = 3,
            n = 3;
        if (isSparse(array, m, n))
            System.out.println("Yes");
        else
            System.out.println("No");
    }
}
 
// This code is contributed by
// Nikita Tiwari.


Output:  

Yes

Time complexity: O(m*n) where m is no of rows and n is no of columns of matrix

Auxiliary Space: O(1)

Please refer complete article on Check if a given matrix is sparse or not for more details!

Dominic
Dominichttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

1 COMMENT

Most Popular

Dominic
32493 POSTS0 COMMENTS
Milvus
126 POSTS0 COMMENTS
Nango Kala
6864 POSTS0 COMMENTS
Nicole Veronica
11990 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12084 POSTS0 COMMENTS
Shaida Kate Naidoo
7000 POSTS0 COMMENTS
Ted Musemwa
7241 POSTS0 COMMENTS
Thapelo Manthata
6951 POSTS0 COMMENTS
Umr Jansen
6936 POSTS0 COMMENTS