leetcode

Count Negative Numbers in a Sorted Matrix - Link

Question Description

Given a m x n matrix grid which is sorted in non-increasing order both row-wise and column-wise, return the number of negative numbers in grid.


Constraints


Approach

The matrix is sorted in non-increasing order both row-wise and column-wise, meaning each row and each column is sorted in decreasing order. This property can be used to optimize the search for negative numbers, potentially using binary search on each row to find the first negative number and count from there.

However, the provided solution uses a brute force approach, iterating through all elements and counting negatives.


Examples

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 negative numbers in the matrix.

Example 2:

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


Solution

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

Time and Space Complexity

Back to All Problems