Problem Description
Given an m x n matrix grid that is sorted in non-increasing order both row-wise and column-wise, count and return the number of negative numbers in grid.
Key Insights
- Each row is sorted in non-increasing order, meaning that once a negative number is encountered, all elements to its right in that row are also negative.
- The matrix’s columns are also sorted in non-increasing order, allowing an efficient traversal starting from a strategic position.
- The optimal O(m + n) approach starts from the bottom-left of the matrix and moves either up or right based on the sign of the current element.
- If the current element is negative, all elements to its right in that row are negative; if it is non-negative, move right.
Space and Time Complexity
Time Complexity: O(m + n)
Space Complexity: O(1)
Solution
We use the bottom-left traversal method. Start at the bottom-left cell of the matrix. If the current value is negative, then all elements to its right are negative because the row is sorted; hence, add the count of these negatives and move one row up. If the value is non-negative, move one column to the right. Continue this process until the pointers leave the bounds of the matrix. This approach ensures we count all negative numbers efficiently in O(m + n) time with constant extra space.