Problem Statement

Given a m * n matrix grid which is sorted in non-increasing order both row-wise and column-wise.

Return the number of negative numbers in grid. [URL]

Example 1:

Input: grid = [[4,3,2,-1],[3,2,1,-1],[1,1,-1,-2],[-1,-1,-2,-3]]
Output: 8
Explanation: There are 8 negatives number in the matrix.

Example 2:

Input: grid = [[3,2],[1,0]]
Output: 0

Example 3:

Input: grid = [[1,-1],[-1,-1]]
Output: 3

Example 4:

Input: grid = [[-1]]
Output: 1

Constraints:

1. m == grid.length
2. n == grid[i].length
3. 1 <= m, n <= 100
4. -100 <= grid[i][j] <= 100

Approach 1

Brute force

#collapse-hide
from typing import List

class Solution:
    def countNegatives(self, grid: List[List[int]]) -> int:
        res = 0
        for i in range(len(grid)):
            for j in range(len(grid[0])):
                if grid[i][j] < 0:
                        res += 1
        
        return res
sol = Solution()
sol.countNegatives([[4,3,2,-1],[3,2,1,-1],[1,1,-1,-2],[-1,-1,-2,-3]])
8

Worst case performance in Time: $O(m*n)$

Worst case performance in Space: $O(1)$

Approach 2

#collapse-hide

class Solution:
    def countNegatives(self, grid: List[List[int]]) -> int:
        posCount = 0
        noOfElements = len(grid) * len(grid[0])
        for i in range(len(grid)):
            for j in range(len(grid[0])):
                if grid[i][j] < 0:
                    break
                else:
                    posCount += 1
        return noOfElements - posCount
sol = Solution()
sol.countNegatives([[4,3,2,-1],[3,2,1,-1],[1,1,-1,-2],[-1,-1,-2,-3]])
8

Worst case performance in Time: $O(m*n)$

Worst case performance in Space: $O(1)$

Approach 3

#collapse-hide

class Solution:
    def countNegatives(self, grid: List[List[int]]) -> int:
        i, j = len(grid)-1, 0
        count = 0
        while i >= 0 and j < len(grid[0]):
            if grid[i][j] < 0:                
                count += (len(grid[0]) - j)
                i -= 1
            else:
                j += 1
        
        return count
                
sol = Solution()
sol.countNegatives([[4,3,2,-1],[3,2,1,-1],[1,1,-1,-2],[-1,-1,-2,-3]])
8

Worst case performance in Time: $O(m+n)$

Worst case performance in Space: $O(1)$