Count Negative Numbers in a Sorted Matrix

EasyMatrixtwo pointers

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

You are given an m x n integer matrix grid in which every row and every column is sorted in **non-increasing** order (values never go up as you move right or down). Return the total number of strictly negative entries in grid. An O(m + n) staircase walk is possible; O(m log n) with binary search per row is also fine.

Examples

Input: grid = [[4,3,2,-1],[3,2,1,-1],[1,1,-1,-2],[-1,-1,-2,-3]]
Output: 8
Rows contain 1, 1, 2, and 4 negatives respectively.
Input: grid = [[3,2],[1,0]]
Output: 0
0 is not negative, so there are none.

Constraints

  • 1 <= m, n <= 100
  • -100 <= grid[i][j] <= 100
  • Every row and column of `grid` is sorted in non-increasing order.

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More two pointers problems