Total Negative Numbers In A Sorted Matrix

Easy
0/40
profile
Contributed by
11 upvotes
Asked in company
Dell India

Problem statement

You are given an ‘N’ x ‘M’ matrix ‘MAT’, which is sorted in non-increasing order both row-wise and column-wise. Your task is to count the number of negative numbers in ‘MAT’.

For Example:

You are given ‘N’ = 3, ‘M’ = 2 and ‘MAT’= [[3, 1],[2, -1],[1, 2]]. Then the answer will be two for the first test case because there are two negative numbers in the given matrix(-1, -2).
Detailed explanation ( Input/output format, Notes, Images )
Input Format :
The first line of the input contains a single integer 'T', representing the number of test cases.

The first line of each test case contains two space-separated integers, ‘N’ and ‘M’, representing the number of rows and columns in ‘MAT’, respectively.

The next ‘N’ lines contain ‘M’ space-separated integers representing the elements of ‘MAT’.
Output Format:
For each test case, print the number of negative numbers in ‘MAT’.

Print the output of each test case in a separate line.
Note:
You do not need to print anything. It has already been taken care of. Just implement the given function.
Constraints:
1 <= T <= 10
1 <= N <= 5000
1 <= M <= 5000
-10^6 <= MAT[i][j] <= 10^6

Time Limit: 1 sec
Sample Input 1:
2
3 2
3 1 
2 -1
1 -2
3 3
3 2 1
0 -1 -2
-3 -4 -5
Sample Output 1:
2
5
Explanation of Sample Input 1:
For the first test case, the answer will be two for the first test case because there are two negative numbers in the given matrix(-1, -2).

For the second test case, the answer will be five because there are five negative numbers in the given matrix(-1, -2, -3, -4, -5).
Sample Input 2:
2
2 2
3 -1 
2 -1
2 2
1 1 
1 1
Sample Output 2:
2
0
Hint

Check every element of the matrix.

Approaches (3)
Brute Force

In this approach, we will check every element of the matrix, and for each negative number, we will increment our answer by 1. We will use two nested loops to traverse the given matrix and a variable ‘COUNT’ to store the count of the negative numbers. The final value of ‘COUNT’ will be our answer.

 

Algorithm :

  • Initialize a variable ‘COUNT’ to store the count of negative numbers.
  • Iterate ‘I’ in 0 to ‘MAT.LENGTH’:
    • Iterate ‘J’ in 0 to ‘MAT[0].LENGTH’:
      • If ‘MAT’[‘I’][‘J’] is less than 0, increment ‘COUNT’ by 1.
  • Return ‘COUNT’.
Time Complexity

O(N * M), where 'N' and 'M' are the number of rows and columns of the matrix, respectively.
 

We have to traverse the ‘N’ x ‘M’ matrix, which will take O(N * M) time. Hence, the total time complexity is O(N * M).

Space Complexity

O(1).

 

Only a constant amount of extra space is being used. Hence, the total space complexity is O(1).

Code Solution
(100% EXP penalty)
Total Negative Numbers In A Sorted Matrix
Full screen
Console