EasyArrayBinary SearchMatrix

Count Negative Numbers in a Sorted Matrix

LeetCode
1 approach, code in all languages

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
You've got the patterns

Patterns get you through the screen. Shipping gets you hired.

FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.

750+ engineers trained · frontend, backend, AWS & AI

August 15 · 0d left
Enroll Now