Count Negative Numbers in a Sorted Matrix - Problem

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.

The matrix is sorted such that:

  • Each row is sorted in non-increasing order from left to right
  • Each column is sorted in non-increasing order from top to bottom

This means larger numbers appear in the top-left, and smaller (potentially negative) numbers appear in the bottom-right.

Input & Output

Example 1 — Basic Case
$ Input: grid = [[4,3,-1],[-3,-4,-5]]
Output: 4
💡 Note: Row 1 has 1 negative number (-1), Row 2 has 3 negative numbers (-3, -4, -5). Total = 1 + 3 = 4
Example 2 — All Positive
$ Input: grid = [[3,2],[1,0]]
Output: 0
💡 Note: All numbers in the matrix are non-negative, so the count is 0
Example 3 — Mixed Pattern
$ Input: grid = [[1,-1],[-1,-1]]
Output: 3
💡 Note: Row 1 has 1 negative (-1), Row 2 has 2 negatives (-1, -1). Total = 1 + 2 = 3

Constraints

  • m == grid.length
  • n == grid[i].length
  • 1 ≤ m, n ≤ 100
  • -100 ≤ grid[i][j] ≤ 100

Visualization

Tap to expand
Count Negative Numbers in Sorted MatrixInput Matrix:43-1-31-2-5-7✓ Positive✗ NegativeMatrix is sorted: rows and columns decrease left-to-right and top-to-bottomCount negative numbers: -1, -3, -2, -5, -7Result: 5 negative numbers found
Understanding the Visualization
1
Input
Sorted matrix with decreasing values
2
Strategy
Use sorting to skip entire regions
3
Output
Total count of negative numbers
Key Takeaway
🎯 Key Insight: Use the sorted matrix property to eliminate entire rows or columns at once instead of checking every element
Asked in
Amazon 25 Microsoft 18 Google 15
28.5K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen