Problem
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
.
Examples
Example 1:
$$ \begin{bmatrix}
4 & 3 & 2 & -1 \\
3 & 2 & 1 & -1 \\
1 & 1 & -1 & -2 \\
-1 & -1 & -2 & -3
\end{bmatrix} $$
|
|
Example 2:
|
|
Solution
Method 1 - Naive
The naive approach involves iterating through each element of the matrix grid
and counting all negative elements one by one. This straightforward approach checks each element individually.
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(m * n)
- 🧺 Space complexity:
O(1)
Method 2 - Optimal Solution
Given that the matrix grid
is sorted in non-increasing order both row-wise and column-wise, we can use this property to optimize the search for negative numbers.
$$ \begin{bmatrix} 4 & 3 & 2 & -1 \\ 3 & 2 & 1 & -1 \\ 1 & 1 & -1 & -2 \\ -1 & -1 & -2 & -3 \end{bmatrix} $$
Start from the bottom-left corner of the grid (in above matrix it is -3):
- If the current element is negative, all elements above it in the same column are also negative.
- If the current element is non-negative, move right to the next element in the same row.
- Continue until all possible negatives are counted.
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(m + n)
- 🧺 Space complexity:
O(1)