Last active
December 28, 2025 18:03
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * @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; | |
| }; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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