### 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**- Spiral Order Matrix 1
- Anti Diagonals
- Diagonal Traverse
- How to check if given sudoku is valid or not
- Detect Cycle in Linked List

## Comments

## Post a Comment