Leetcode 1351. Count Negative Numbers in a Sorted Matrix
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 the matrix.
Before we jump into coding, let’s clarify a few things about the problem statement:
grid
contain zeros and positive values?A brute force method would be to iterate over every element in the matrix to count the negative numbers. However, since the matrix is sorted in non-increasing order, we can take advantage of this property to come up with a more efficient approach.
Here’s a more optimal strategy we can use:
This way, we minimize the number of elements we need to check, leading to a more efficient solution.
Here’s the implementation of the described strategy in C++:
#include <vector>
class Solution {
public:
int countNegatives(std::vector<std::vector<int>>& grid) {
int m = grid.size();
int n = grid[0].size();
int count = 0;
int row = 0, col = n - 1; // Start from the top-right corner of the matrix
while(row < m && col >= 0) {
if(grid[row][col] < 0) {
// If grid[row][col] is negative, all elements below in the same column are negative.
count += (m - row);
col--; // Move left
} else {
// Move down.
row++;
}
}
return count;
}
};
The time complexity of this approach is O(m + n), where m
is the number of rows and n
is the number of columns in the matrix. This is because, in the worst case, we might need to traverse each row and each column at most once. Hence, this solution is much more efficient than the brute-force approach which would have a time complexity of O(m * n).
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?