Count Negative Numbers in a Sorted Matrix (LeetCode 1351): Solution and Explanation
A grid has every row and every column sorted in non-increasing order. Count how many of its values are negative.
Intuition
In a sorted row the negatives sit together at the right end, so a row is fully described by where its negative tail starts. Counting is the same as finding that boundary in every row.
The columns are sorted too, which means the boundary only moves left as you go down. Put together, the boundaries form a staircase running from the top-right toward the bottom-left.
Start at the bottom-left cell. If it is negative, the whole rest of that row is negative, so add those cells and move up. If it is not negative, then nothing above it in that column can be negative, so move right. Every comparison throws away a full row or a full column.
Approach: Staircase walk from the bottom-left corner
- Set
r = m - 1,c = 0andcount = 0. - While
r >= 0andc < n, look atgrid[r][c]. - If it is negative, add
n - ctocount(the cell and everything to its right) and move up withr -= 1. - Otherwise move right with
c += 1, because this column holds no negatives from rowrupward. - When the pointer leaves the grid, return
count.
Step-by-step example
grid = [[4,3,2,-1],[3,2,1,-1],[1,1,-1,-2],[-1,-1,-2,-3]]
- Start at (3, 0) = -1. It is negative, so all 4 cells of row 3 count: count = 4. Move up to (2, 0).
- (2, 0) = 1 is not negative, move right. (2, 1) = 1, move right again.
- (2, 2) = -1 is negative: row 2 has 2 negatives from column 2, count = 6. Move up to (1, 2).
- (1, 2) = 1, move right. (1, 3) = -1 is negative: count = 7, move up to (0, 3).
- (0, 3) = -1 is negative: count = 8, move up. r is now -1, so the walk ends with 8.
Code: Python, Java, C++
1class Solution:
2 def countNegatives(self, grid: List[List[int]]) -> int:
3 m, n = len(grid), len(grid[0])
4 r, c = m - 1, 0
5 count = 0
6 while r >= 0 and c < n:
7 if grid[r][c] < 0:
8 count += n - c
9 r -= 1
10 else:
11 c += 1
12 return count1class Solution {
2 public int countNegatives(int[][] grid) {
3 int m = grid.length, n = grid[0].length;
4 int r = m - 1, c = 0;
5 int count = 0;
6 while (r >= 0 && c < n) {
7 if (grid[r][c] < 0) {
8 count += n - c;
9 r--;
10 } else {
11 c++;
12 }
13 }
14 return count;
15 }
16}1class Solution {
2public:
3 int countNegatives(vector<vector<int>>& grid) {
4 int m = grid.size(), n = grid[0].size();
5 int r = m - 1, c = 0;
6 int count = 0;
7 while (r >= 0 && c < n) {
8 if (grid[r][c] < 0) {
9 count += n - c;
10 r--;
11 } else {
12 c++;
13 }
14 }
15 return count;
16 }
17};Time and space complexity
O(m + n)
Each step either moves up a row or right a column, so there are at most m + n steps.
O(1)
Only two indices and the running count are stored.
Other approaches
Binary search in every row (time O(m log n), space O(1))
For each row, binary search for the first negative value and add the length of the tail. It only uses the row ordering and is a good answer if the columns were not sorted.
Scan every cell (time O(m * n), space O(1))
Check each value and count the negatives. It is correct and simple but ignores the sorting entirely.
Common mistakes
- Starting at the top-left or bottom-right corner. From those cells both moves change the value in the same direction, so one comparison does not tell you which way to go.
- Treating 0 as negative. The check must be
< 0, not<= 0. - Adding 1 instead of
n - cwhen a negative is found, which forgets the rest of the row. - Using
grid[0].lengthwithout care in languages where an empty grid is possible. LeetCode guarantees at least one row and one column, so it is safe here.
Frequently asked questions
Why does the walk start at the bottom-left corner?
From there, moving up makes values larger and moving right makes them smaller. So a negative tells you to go up and a non-negative tells you to go right, and either way you discard a whole row or column. The top-right corner works too, mirrored.
Is the staircase walk faster than binary search per row?
It is O(m + n) against O(m log n). For a square grid that is linear against n log n, so the walk wins as the grid grows.
What if a row has no negatives at all?
The pointer simply walks right past it. When c reaches n the loop ends, and every row still above the pointer contributes nothing, which is correct because their tails start even further right.