Count Negative Integers In A Sorted 2D Array

Problem Statement

 
Given a sorted 2-D array, find the number of negative integers present in the 2-D array. Solving this is pretty easy but the point is that Amazon asked this question in their interview, so it's not just meant to be solved but rather solved efficiently. Let's look at some sample cases, 
  1. int[,] matrix = new int[,]  
  2. {  
  3.     { -5, -3, -2, 0, 4 },  
  4.     { -1, 0, 1, 3, 4 },  
  5.     { 3, 5, 6, 8, 9 },  
  6. };  
  7. int result = CountNegatives(matrix);  
  8. //result should be 4 since it has 4 negative integers

Approach 1

 
The most straightforward way to approach this problem is by looping over all the elements and keeping the count for all the elements less than zero. This approach is rather an inefficient one as its time complexity is,
 
Time Complexity = O(numberOfRows * numberOfColumns)
 
We have to traverse over all the elements until the end of the matrix to check for any negative intergers, hence proving this algorithm is an inefficient one. Here's a sample code in C# that demonstrates this algorithm,
  1. static int Approach1(int[,] matrix)  
  2. {  
  3.     int count = 0;  
  4.     foreach (int element in matrix)  
  5.     {  
  6.         if (element < 0)  
  7.             count++;  
  8.     }  
  9.     return count;  
  10. }  

Approach 2

 
Another way to solve this problem is by looping over the matrix in reverse order and using the given information 'sorted' to make the algorithm more efficient. We loop over every row from the last element to the first, and if we encounter any negative integer we add that index to the counter and then break the loop.
 
Time Complexity = O(numberOfRows + numberOfColumns)
 
This is an efficient solution to this interview question which takes the least time to process. This algorithm is implemented in the C# code below,
  1. static int Approach2(int[,] matrix)  
  2. {  
  3.     int count = 0;  
  4.     for (int row = 0; row < matrix.GetLength(0); row++)  
  5.     {  
  6.         for (int column = matrix.GetLength(1) - 1; column >= 0; column--)  
  7.         {  
  8.             if (matrix[row, column] < 0)  
  9.             {  
  10.                 count += column + 1;  
  11.                 break;  
  12.             }  
  13.         }  
  14.     }  
  15.     return count;  
  16. }