Leetcode 1351. Count Negative Numbers in a Sorted Matrix
You are given an m x n
matrix grid
which is sorted in non-increasing order both row-wise and column-wise, meaning both grid[i]
and grid[j][i]
are sorted in non-increasing order. Return the number of negative numbers in grid
.
Input:
grid = [
[4, 3, 2, -1],
[3, 2, 1, -1],
[1, 1, -1, -2],
[-1, -1, -2, -3]
]
Output:
8
Input:
grid = [
[3, 2],
[1, 0]
]
Output:
0
Q: Can the matrix contain positive numbers as well as zeroes? A: Yes, the matrix can contain positive numbers and zeroes.
Q: Is there a specific data type expected for the output? A: The output should be an integer representing the count of negative numbers.
Q: Are the dimensions (m and n) of the grid always positive integers? A: Yes, the dimensions of the grid are always positive integers greater than 0.
The matrix is sorted in non-increasing order both row-wise and column-wise. This property allows us to use a more efficient approach than checking each element one by one.
grid[0][n-1]
.i
for rows, starting at 0
.j
for columns, starting at n-1
.i
is within the range of rows and j
within the range of columns:
grid[i][j]
is negative, add (m - i)
(remaining elements in this column) to the counter and move left (j--
).grid[i][j]
is not negative, move down (i++
).public class Solution {
public int countNegatives(int[][] grid) {
int m = grid.length;
int n = grid[0].length;
int count = 0;
int i = 0, j = n - 1;
while (i < m && j >= 0) {
if (grid[i][j] < 0) {
// All elements below grid[i][j] in the same column are negative
count += (m - i);
j--;
} else {
i++;
}
}
return count;
}
}
m
rows and n
columns. Each step either moves to the next row or the previous column.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?