Skip to content

Instantly share code, notes, and snippets.

@tatsuyax25
Last active December 28, 2025 18:03
Show Gist options
  • Select an option

  • Save tatsuyax25/cbefde212abe3d1cae2c3e5152353400 to your computer and use it in GitHub Desktop.

Select an option

Save tatsuyax25/cbefde212abe3d1cae2c3e5152353400 to your computer and use it in GitHub Desktop.
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.
/**
* @param {number[][]} grid - A 2D matrix sorted in non-increasing order
* @return {number} - Total count of negative numbers in the matrix
*/
var countNegatives = function (grid) {
let count = 0;
// Loop through each row
for (let row = 0; row < grid.length; row++) {
// Loop through each value in the current row
for (let col = 0; col < grid[row].length; col++) {
// If the value is negative, increment the counter
if (grid[row][col] < 0) {
count++;
}
}
}
return count;
};
class Solution(object):
def countNegatives(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
# Number of rows (m) and columns (n)
m = len(grid)
n = len(grid[0])
# Start at bottom-left corner
row = m - 1
col = 0
count = 0
# Walk while we stay inside the grid
while row >= 0 and col < n:
# If the current value is negative...
if grid[row][col] < 0:
# All values to the RIGHT are also negative because rows are sorted
count += (n - col)
# Move UP to check the next row
row -= 1
else:
# Current value is non-negative, so move RIGHT to find negatives
col += 1
return count
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment