EasyArrayBinary SearchMatrix

1 approach, code in every language

Problem description

You are given a rectangular grid of integers where each row is sorted in non-increasing order from left to right, and each column is sorted in non-increasing order from top to bottom. Determine how many entries in the grid are strictly negative.

Because of the sorted structure, the negative values always cluster toward the bottom-left portion of the grid, which lets you count them without inspecting every cell.

Example 1

Input: grid = [[5, 2, -1], [3, 0, -3], [-2, -4, -6]]

Output: 5

The strictly-negative entries are -1 in the first row, -3 in the second row, and -2, -4, -6 in the third row, which is five cells in total.

Example 2

Input: grid = [[4, 3], [2, 1]]

Output: 0

Every value is positive, so there are no negatives to count.

Constraints

  • 1 <= grid.length, grid[i].length <= 100
  • -100 <= grid[i][j] <= 100
  • Each row is sorted in non-increasing order
  • Each column is sorted in non-increasing order

After the pattern

Now solve one you haven't seen.

Freezing Cells on the Weather Board is our own problem on the technique behind Count Negative Numbers in a Sorted Matrix: a new statement, so there's no answer to remember. Write it in your browser and run it against graded tests.

1,194 problems · 15,062 graded tests · free