Number Negatives in Sorted Matrix
Find the number of negative integers in a matrix that is sorted row-wise and column-wise.
The Idea: We can scan the array in O(n*m) time and count the negatives. Alternatively, we can begin from the top right corner, find the first negative iterating backwards, use that position to find the remaining negatives in that row, and then move down one row, and continue this process until we reach the last row. We have to understand why we can move down a row from the first negative position of the previous row. This can be proved inductively. Consider only two rows. In the case that there are all positives, the algorithm will terminate. In the case of negatives, the position in the second row above the previous negative would have to be greater than or equal to it. That means, if the previous number was negative, the the following number can only be as small as that negative, and since the previous number was the largest negative, the next negative must be >= this element. The same logic can be said about the remaining rows. We can integrate in binary partition to find the next negative given these knew bounds.
Complexity: O(log(n+m)) time (?) Not too sure,
Last updated