Count Negative Numbers in a Sorted Matrix Problem
#1351
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 1351.
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.
Example 1:
Input: grid = [[4,3,2,-1],[3,2,1,-1],[1,1,-1,-2],[-1,-1,-2,-3]]
Output: 8
Explanation: There are 8 negatives number in the matrix.
Example 2:
Input: grid = [[3,2],[1,0]]
Output: 0
Constraints:
m == grid.lengthn == grid[i].length1 <= m, n <= 100-100 <= grid[i][j] <= 100
Follow up: Could you find an O(n + m) solution?
Solution
Approach: Staircase Walk from the Bottom-Left Corner
Rows and columns are both non-increasing, so in each row the negatives form a suffix, and the row's first negative column moves left (or stays) as we go down. Start at the bottom-left cell (m - 1, 0):
- If
grid[i][j] < 0, then this cell and everything to its right in rowiare negative: addn - jand move up a row. The row above starts its negatives at columnjor later, sojcan stay. - Otherwise
grid[i][j] >= 0, and so is every cell above it in columnj: move right.
Stop when we leave the grid. Each step moves up or right, so there are at most m + n steps. This answers the follow-up; a binary search in each row would take O(m log n).
Complexity: O(m + n) time and O(1) extra space.
class Solution:
def countNegatives(self, grid: List[List[int]]) -> int:
m, n = len(grid), len(grid[0])
i, j = m - 1, 0 # start at the bottom-left corner
ans = 0
while i >= 0 and j < n:
if grid[i][j] < 0:
ans += n - j # this cell and everything right of it are negative
i -= 1
else:
j += 1 # everything above this cell is >= 0 too
return ans