In this section we are going to see a python program that counts negative numbers in Row-wise and Column-wise sorted matrix with optimal solution.
Row-wise and column-wise sorted array means, each value at any index is small or equal to the value at the index in next column and next row.
M = [[-40, -12, 1, 5], [-20, -2, 5, 15], [-22, -1, 13, 18], [-12, 0, 15, 38]]
In above matrix M, the first column of first row is -40, which is smaller than the value at next column value in same row i.e. -12 and is also smaller than the value in next row in the same column i.e. -20 and so on.
# The matrix must be sorted in ascending order. If not, the algorithm will not work properly matrix = [ [-40, -12, 1, 5], [-20, -2, 5, 15], [-22, -1, 13, 18], [-12, 0, 15, 38]] # To obtain the number of row rowCount = len(matrix) columnCount = 0 # To obtain the number of column for i in matrix: columnCount += 1 a = 0 b = 0 count_Of_Negative_Integer = 0 while a < rowCount and b < columnCount: if matrix[a][b] >= 0: a += 1 b = 0 else: count_Of_Negative_Integer += 1 b += 1 print("Count of Negative Integers in sorted Matrix is: ",count_Of_Negative_Integer)
Count of Negative Integers in sorted Matrix is: 7
In above program,
>=0: first we try to find the count of negative integer, less than 0.
Because in above program, we are trying to get negative integers, however, same program can be used to find the count of integer that is less than any particular integers(n). For example to find the count of integer that is less than or equal to 5 using >5.