The "Count Negative Numbers in a Sorted Matrix" coding problem asks you to find the total count of negative integers in an matrix. The matrix has a special property: both its rows and columns are sorted in non-increasing order (from largest to smallest).
This is a classic "Easy" question used by Microsoft, Amazon, and Google to see if a candidate can move beyond a brute-force solution. It tests your ability to leverage the sorted property of a matrix to achieve a better time complexity, specifically .
While you can use Binary Search on each row for an solution, the most efficient pattern is the Staircase Search or Two Pointers pattern. Starting from the bottom-left corner (or top-right), you can navigate the boundary between positive and negative numbers. If a number is negative, all numbers to its right in that row are also negative. You add that count and move up a row. If it's non-negative, you move right to find the first negative number.
Matrix:
[ [ 4, 3, 2, -1],
[ 3, 2, 1, -1],
[ 1, 1, -1, -2],
[-1, -1, -2, -3] ]
A frequent mistake is not using the sorted property and just iterating through every element, which is inefficient. Another is getting the staircase logic backwards (moving left when you should move right) or hitting an infinite loop by not updating the row/column pointers correctly.
Whenever you see a matrix that is "sorted by rows and columns," think about the Staircase Search. It's almost always the optimal way to find targets or boundaries in linear time relative to the sum of the dimensions.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Find a Peak Element II | Medium | Solve | |
| Search a 2D Matrix | Medium | Solve | |
| Median of a Row Wise Sorted Matrix | Medium | Solve | |
| Leftmost Column with at Least a One | Medium | Solve | |
| Maximum Side Length of a Square with Sum Less than or Equal to Threshold | Medium | Solve |