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

Java Program to Convert Binary to Decimal - The Coding Shala

N-th Tribonacci Number Solution - The Coding Shala

Shell Script to Create a Simple Calculator - The Coding Shala

Shell Script to find sum, product and average of given numbers - The Coding Shala

Introduction to Kotlin Programming Language for Backend Development - The Coding Shala