Count Negative Numbers in a Sorted Matrix

Staircase walk from the bottom-left, counting an entire row tail or stepping up.

Easy
Time O(m + n) Space O(1)
LeetCode
3 min read
matrix two-pointers

Problem#

Given an m x n matrix sorted in non-increasing order both per-row and per-column, return the count of negative numbers.

Examples#

  • [[4,3,2,-1],[3,2,1,-1],[1,1,-1,-2],[-1,-1,-2,-3]]8
  • [[3,2],[1,0]]0

Constraints#

  • m == grid.length, n == grid[i].length, 1 <= m, n <= 100.

Approach#

Start at the bottom-left. If the current cell is negative, all cells to its right in this row are negative too (each row is sorted descending): add n - col and move up. Otherwise, move right.

Solution#

Count Negative Numbers in a Sorted Matrix
class Solution {
public:
int countNegatives(vector<vector<int>>& grid) {
int m = grid.size(), n = grid[0].size();
int r = m - 1, c = 0, count = 0;
while (r >= 0 && c < n) {
if (grid[r][c] < 0) {
count += n - c;
--r;
} else {
++c;
}
}
return count;
}
};

Editorial#

The bottom-left corner is the smallest cell in its row and the largest in its column — a perfect pivot to advance one step at a time. Each step removes a full row or column, so the total work is O(m + n).

Complexity#

  • Time: O(m + n).
  • Space: O(1).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.