Count Negative Numbers in a Sorted Matrix

Leetcode Daily Challenge (8th June, 2023)

Count Negative Numbers in a Sorted Matrix

Problem Statement:-

Given a m x n matrix grid which is sorted in non-increasing order both row-wise and column-wise, return the number of negative numbers in grid.

Link: https://leetcode.com/problems/count-negative-numbers-in-a-sorted-matrix/description/

Problem Explanation with examples:-

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

Constraints

  • m == grid.length

  • n == grid[i].length

  • 1 <= m, n <= 100

  • -100 <= grid[i][j] <= 100

Intuition:-

  • Simply iterate over the grid and count the number of negative numbers.

Solution:-

  • Initialize a variable c to 0.

  • Iterate over the grid and check if the current element is negative. If yes, then increment c by 1.

  • Return c.

Code:-

JAVA Solution

class Solution {
    public int countNegatives(int[][] grid) {
        int count = 0;

        for (int[] row : grid) {
            for (int num : row) {
                if (num < 0) {
                    count++;
                }
            }
        }
        return count;
    }
}

Python Solution

class Solution:
    def countNegatives(self, grid: List[List[int]]) -> int:
        c = 0
        for i in grid:
            for j in i:
                if j < 0:
                    c += 1
        return c

Complexity Analysis:-

TIME:-

The time complexity is O(m*n) where m is the number of rows and n is the number of columns in the grid. We are iterating over the entire grid.

SPACE:-

The space complexity is O(1) as we are not using any extra space. We are just using a variable c to store the count of negative numbers.

References:-

  • Loops

Connect with me:-

Did you find this article valuable?

Support Leeting-LCS by becoming a sponsor. Any amount is appreciated!