Count Negative Numbers in a Sorted Matrix - Problem
You are given an m x n matrix grid that is sorted in non-increasing order both row-wise and column-wise. This means each row reads from largest to smallest (left to right), and each column also reads from largest to smallest (top to bottom).
Your task is to efficiently count how many negative numbers exist in this sorted matrix.
Example: In the matrix [[4,3,2,-1],[3,2,1,-1],[1,1,-1,-2],[-1,-1,-2,-3]], there are 8 negative numbers.
The key insight is leveraging the sorted property to avoid checking every single element - can you find a way to count negatives faster than O(m×n)?
Input & Output
example_1.py — Standard 4x4 Matrix
$
Input:
grid = [[4,3,2,-1],[3,2,1,-1],[1,1,-1,-2],[-1,-1,-2,-3]]
›
Output:
8
💡 Note:
There are 8 negative numbers in the matrix: the -1 in positions (0,3) and (1,3), the -1 and -2 in positions (2,2) and (2,3), and all four numbers in the last row are negative.
example_2.py — Single Row Matrix
$
Input:
grid = [[3,2]]
›
Output:
0
💡 Note:
All numbers in the matrix are positive, so there are no negative numbers to count.
example_3.py — All Negative Matrix
$
Input:
grid = [[-1,-2],[-3,-4]]
›
Output:
4
💡 Note:
All numbers in the 2x2 matrix are negative, so we count all 4 elements.
Constraints
- m == grid.length
- n == grid[i].length
- 1 ≤ m, n ≤ 100
- -100 ≤ grid[i][j] ≤ 100
- grid is sorted in non-increasing order both row-wise and column-wise
Visualization
Tap to expand
Understanding the Visualization
1
Start at the boundary
Begin at top-right where temperature transitions happen
2
Make smart decisions
If current reading is below freezing, all readings below it are also below freezing
3
Follow the staircase
Move left when cold, move down when hot, tracing the freeze line
Key Takeaway
🎯 Key Insight: The sorted property creates a natural boundary between positive and negative regions. By walking this boundary instead of checking every cell, we can count negatives in optimal O(m+n) time!
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code