Coding Problem 11

                            Count Negative Numbers

                                                       asked by Amazon


Ques. Count the number of negative integers in the matrix. The matrix is given in such a way that the number of negative integers is one row is always greater than the next row.

For example - [ [-3, -2, -1, 1], 

                         [ -2,  2, 3, 4 ], 

                         [ 4,  5,  7, 8 ]]

should return 4


Solution.

One naive way to solve this problem is to iterate the every row and columns and increment the count if found integer is negative but this solution has more time complexity i.e.  O(n^2).

So we are going to use the property of matrix given in question. We know that the number of negative integers in one row are more than the next one. 

We start from the first row and last column and find the position of last negative integer in that row and add that value to the counter. Next we will go to the next row but the we will start from the column where we got the last negative integer in previous row and then we will find the position of last negative integer in the second row. We keep repeating this process until we either run out of negative numbers or we get the last row.Lets see the code - 


def sol(M,n,m):

    count = 0

    i = 0            #initially first row

    j = m-1          #initially last column

    while j >= 0 and i < n:

        # if value is negative then add the column value and increment row pointer

        if M[i][j] < 0:   

    count += (j+1)

    i+=1

        # otherwise decrement the column pointer

        else:

    j-=1

    return count


mat = [ [-3, -2, -1, 1],  [-2, 2, 3, 4],  [4, 5, 7, 8]]

print(sol(mat, 3, 4))


Output : 4

Comments

Popular posts from this blog

Coding Problem 10

Coding Problem 3

Coding Problem 9