431. Count Negative Numbers in Sorted Matrix

EasyBinary SearchArrayBinary SearchMatrix

Given a m x n matrix grid where each row is sorted in non-increasing order and each column is sorted in non-increasing order, return the number of negative numbers in grid. Solve in O(m log n) using binary search per row.

Input: A 2D integer matrix grid sorted non-increasingly per row.

Output: Count of negative numbers in the grid.

Examples

Example 1
Input: [[4,3,2,-1],[3,2,1,-1],[1,1,-1,-2],[-1,-1,-2,-3]]
Output: 8
Explanation: Row 0: 1 negative. Row 1: 1 negative. Row 2: 2 negatives. Row 3: 4 negatives. Total=8.
Example 2
Input: [[3,2],[1,0]]
Output: 0
Explanation: No negative numbers.
Example 3
Input: [[-1]]
Output: 1
Explanation: Single negative element.

Constraints

Asked by

AmazonMetaMicrosoftBloombergGoogle
Solve this problem in the editor →