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
.
For example:
grid = [[4,3,2,-1],[3,2,1,-1],[1,1,-1,-2],[-1,-1,-2,-3]]
In the example above, the correct answer would be 8, because there are 8 negative numbers in the matrix.
As another example:
grid = [[3,2],[1,0]]
Here, the correct answer is 0, because there are no negative numbers in the matrix.
m == grid.length
n == grid[i].length
1 <= m, n <= 100
-100 <= grid[i][j] <= 100
Can you provide an efficient algorithm to solve this problem? Additionally, can you identify the time and space complexity of your solution? Finally, is there a way to find an O(n + m) solution?
The most straightforward approach is to iterate through each element of the grid and check if it's negative. If it is, increment a counter.
def count_negatives_brute_force(grid):
count = 0
for row in grid:
for num in row:
if num < 0:
count += 1
return count
The brute-force solution iterates through each element of the m x n
grid once. Therefore, the time complexity is O(m * n).
The space complexity is O(1) because it only uses a constant amount of extra space for the counter.
Since the grid is sorted in non-increasing order both row-wise and column-wise, we can use this property to optimize our search. We can start from the bottom-left element and move either up (if the current element is non-negative) or right (if the current element is negative).
row
to m - 1
and col
to 0.count
to 0.row >= 0
and col < n
:
grid[row][col] < 0
:
count
by n - col
(all elements to the right in the current row are negative).row
to move up to the next row.col
to move right to the next column.count
.def count_negatives_optimal(grid):
m = len(grid)
n = len(grid[0])
row = m - 1
col = 0
count = 0
while row >= 0 and col < n:
if grid[row][col] < 0:
count += n - col
row -= 1
else:
col += 1
return count
The optimal solution traverses the grid in a way that either row
decreases or col
increases in each step. In the worst case, it can traverse all rows and columns, resulting in a time complexity of O(m + n).
The space complexity is O(1) because we only use a constant amount of extra space for variables.
Both the brute force and optimal solutions can handle these edge cases correctly.