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 called a sparse matrix. So, we aim to count the number of 0s present in the matrix. If they are more than half of the elements in the matrix then print YES, else NO as output.
Input: 1 0 3 0 0 4 6 0 0 Output: Yes Explaination:There are 5 zeros in the matrix which is more than half of the matrix size. Input: 1 2 3 0 7 8 5 0 7 Output: No Explaination:There are 2 zeros in the matrix which is less than half of the matrix size.
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 then print Yes else No. There are two approaches to do so.
In this approach, we will check whether a matrix is a sparse matrix or not.
- Take the matrix.
- Traverse the matrix’s element one by one and counting the number of zeros.
- Checking if the count is more than (m*n)/2, if yes else no.
Below is the implementation of the above approach:
Time Complexity: O(m*n)
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready.