Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Build confidence with an intuition-first walkthrough focused on array fundamentals.
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] <= 100O(n + m) solution?Problem summary: 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.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Binary Search
[[4,3,2,-1],[3,2,1,-1],[1,1,-1,-2],[-1,-1,-2,-3]]
[[3,2],[1,0]]
maximum-count-of-positive-integer-and-negative-integer)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #1351: Count Negative Numbers in a Sorted Matrix
class Solution {
public int countNegatives(int[][] grid) {
int m = grid.length;
int n = grid[0].length;
int i = m - 1;
int j = 0;
int ans = 0;
while (i >= 0 && j < n) {
if (grid[i][j] >= 0) {
j++;
} else {
ans += n - j;
i--;
}
}
return ans;
}
}
// Accepted solution for LeetCode #1351: Count Negative Numbers in a Sorted Matrix
func countNegatives(grid [][]int) (ans int) {
m := len(grid)
n := len(grid[0])
i := m - 1
j := 0
for i >= 0 && j < n {
if grid[i][j] >= 0 {
j++
} else {
ans += n - j
i--
}
}
return
}
# Accepted solution for LeetCode #1351: Count Negative Numbers in a Sorted Matrix
class Solution:
def countNegatives(self, grid: List[List[int]]) -> int:
m, n = len(grid), len(grid[0])
i, j = m - 1, 0
ans = 0
while i >= 0 and j < n:
if grid[i][j] >= 0:
j += 1
else:
ans += n - j
i -= 1
return ans
// Accepted solution for LeetCode #1351: Count Negative Numbers in a Sorted Matrix
impl Solution {
pub fn count_negatives(grid: Vec<Vec<i32>>) -> i32 {
let m = grid.len();
let n = grid[0].len();
let mut i: i32 = m as i32 - 1;
let mut j: usize = 0;
let mut ans: i32 = 0;
while i >= 0 && j < n {
if grid[i as usize][j] >= 0 {
j += 1;
} else {
ans += (n - j) as i32;
i -= 1;
}
}
ans
}
}
// Accepted solution for LeetCode #1351: Count Negative Numbers in a Sorted Matrix
function countNegatives(grid: number[][]): number {
const m = grid.length;
const n = grid[0].length;
let i = m - 1;
let j = 0;
let ans = 0;
while (i >= 0 && j < n) {
if (grid[i][j] >= 0) {
j++;
} else {
ans += n - j;
i--;
}
}
return ans;
}
Use this to step through a reusable interview workflow for this problem.
Check every element from left to right until we find the target or exhaust the array. Each comparison is O(1), and we may visit all n elements, giving O(n). No extra space needed.
Each comparison eliminates half the remaining search space. After k comparisons, the space is n/2ᵏ. We stop when the space is 1, so k = log₂ n. No extra memory needed — just two pointers (lo, hi).
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Wrong move: Setting `lo = mid` or `hi = mid` can stall and create an infinite loop.
Usually fails on: Two-element ranges never converge.
Fix: Use `lo = mid + 1` or `hi = mid - 1` where appropriate.