Leetcode 1351: Count Negative Numbers in a Sorted Matrix

grid47
grid47
Exploring patterns and algorithms
Jun 24, 2024 5 min read

You are given an m x n matrix grid, sorted in non-increasing order both row-wise and column-wise. Your task is to determine how many negative numbers are present in the grid.
Problem
Approach
Steps
Complexity
Input: The input consists of a matrix grid where each row and each column is sorted in non-increasing order.
Example: For example, [[7,5,3,-1], [6,4,2,-1], [3,1,-2,-3], [-1,-2,-3,-4]].
Constraints:
• 1 <= m, n <= 100
• -100 <= grid[i][j] <= 100
Output: The output should be an integer representing the count of negative numbers in the grid.
Example: For example, in the matrix [[7,5,3,-1], [6,4,2,-1], [3,1,-2,-3], [-1,-2,-3,-4]], the output would be 8.
Constraints:
• The result should be an integer representing the number of negative numbers.
Goal: To count the number of negative numbers in the grid by efficiently checking each row and column.
Steps:
• 1. Iterate through each row of the matrix.
• 2. For each row, use binary search or a direct check to count how many negative numbers are present.
• 3. Sum the results for each row to get the total count of negative numbers.
Goal: The matrix is sorted in non-increasing order both row-wise and column-wise.
Steps:
• 1 <= m, n <= 100
• -100 <= grid[i][j] <= 100
Assumptions:
• The matrix is always sorted in non-increasing order both row-wise and column-wise.
• All values in the grid are integers.
Input: Example 1: grid = [[7, 5, 3, -1], [6, 4, 2, -1], [3, 1, -2, -3], [-1, -2, -3, -4]]
Explanation: In this matrix, there are 8 negative numbers, which are counted and returned as the result.

Input: Example 2: grid = [[1, 0], [0, 0]]
Explanation: This matrix has no negative numbers, so the result is 0.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus