Count Negative Numbers in a Sorted Matrix

We can iterate through the 2D grid, counting the number of negative numbers. In Python, we use list comprehension and the built-in sum function.

Here’s how you could solve the problem:

1
2
3
class Solution:
    def countNegatives(self, grid: List[List[int]]) -> int:
        return sum(val < 0 for row in grid for val in row)

In this solution, val < 0 for row in grid for val in row generates a list of boolean values, where True (which is equivalent to 1) indicates that the number is negative and False (equivalent to 0) indicates that the number is non-negative. The sum function then adds up these values, effectively counting the number of True values, which is the number of negative numbers in the grid.

Identifying Problem Isomorphism

“Count Negative Numbers in a Sorted Matrix” (#1351 on LeetCode) involves counting the number of negative numbers in a matrix that is sorted in non-increasing order both row-wise and column-wise.

An isomorphic problem to this is “Kth Smallest Element in a Sorted Matrix” (#378 on LeetCode). In this problem, you are given a n x n matrix where each of the rows and columns are sorted in ascending order, and you are asked to find the kth smallest element in the matrix.

In both problems, you are working with matrices that are sorted row-wise and column-wise. In “Count Negative Numbers in a Sorted Matrix”, you are counting the number of negative elements, while in “Kth Smallest Element in a Sorted Matrix”, you are finding the kth smallest element. The problems share similarities in the way they traverse the sorted matrix and perform operations based on the values of the elements.

“Kth Smallest Element in a Sorted Matrix” is more complex because it requires not only traversing the matrix but also keeping track of the kth smallest element, whereas “Count Negative Numbers in a Sorted Matrix” is simpler as it only involves counting the negative numbers.