You’re given an m x n
matrix grid
which is sorted in non-increasing order both row-wise and column-wise. Your task is to count the number of negative numbers in the grid.
Example:
Input: grid = [[4,3,2,-1],[3,2,1,-1],[1,1,-1,-2],[-1,-1,-2,-3]]
Output: 8
0
as there are no elements to count.1 <= m, n <= 100
.Since the grid is sorted in non-increasing order both row-wise and column-wise:
This strategy takes advantage of the sorted nature to ensure every element less than a known negative value is also counted efficiently.
def countNegatives(grid):
m, n = len(grid), len(grid[0])
count = 0
row, col = m - 1, 0
while row >= 0 and col < n:
if grid[row][col] < 0:
count += (n - col) # all the elements to the right in this row are negative
row -= 1 # move up to the previous row
else:
col += 1 # move right to the next column
return count
O(m + n)
- In the worst case, we traverse each row and column at most once.O(1)
- We use only a few extra variables for counting and indexing.This approach is efficient for large matrices because it leverages the sorting property to avoid unnecessary checks.
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?