Count Negative Numbers in a Sorted Matrix Java Program - The Coding Shala

Home >> Java Program >> Count Negative Numbers in a Sorted Matrix

 In this post, we are going to write a Java Program to Count Negative Numbers in a Sorted Matrix.

Count Negative Numbers in a Sorted Matrix Problem

Given an m * n matrix grid which is sorted in non-increasing order both row-wise and column-wise. Return the number of negative numbers in the grid.

Example 1:
Input: grid = [[4,3,2,-1],[3,2,1,-1],[1,1,-1,-2],[-1,-1,-2,-3]]
Output: 8
Explanation: There are 8 negatives numbers in the matrix.

Example 2:
Input: grid = [[3,2],[1,0]]
Output: 0

Example 3:
Input: grid = [[1,-1],[-1,-1]]
Output: 3

Count Negative Numbers in a Sorted Matrix Java Solution

Approach 1

By using two loops, we will check every element and count the negative numbers.

We can improve this approach as we know the matrix is sorted, so in each row, if we get a negative number then the rest of the elements in that row will be negative.

Java Program: 

class Solution {
    public int countNegatives(int[][] grid) {
        int ans = 0;
        for(int i=0;i<grid.length;i++){
            for(int j=0;j<grid[i].length;j++){
                if(grid[i][j]<0){
                    ans += grid[i].length - j;
                    break;
                }
            }
        }
        return ans;
    }
}

Other Posts You May Like
Please leave a comment below if you like this post or found some errors, it will help me to improve my content.

Comments

Popular Posts from this Blog

N-th Tribonacci Number Solution - The Coding Shala

Find Second Smallest Element in the Array - The Coding Shala

Graph Representation using Adjacency Matrix - The Coding Shala

Time Complexity, Space Complexity, Asymptotic Notations - The Coding Shala

Java Method Overloading - The Coding Shala