Count Negative Numbers in a Sorted Matrix - Problem

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.

The matrix is sorted such that:

  • Each row is sorted in non-increasing order from left to right
  • Each column is sorted in non-increasing order from top to bottom

This means larger numbers appear in the top-left, and smaller (potentially negative) numbers appear in the bottom-right.

Input & Output

Example 1 — Basic Case
$ Input: grid = [[4,3,-1],[-3,-4,-5]]
Output: 4
💡 Note: Row 1 has 1 negative number (-1), Row 2 has 3 negative numbers (-3, -4, -5). Total = 1 + 3 = 4
Example 2 — All Positive
$ Input: grid = [[3,2],[1,0]]
Output: 0
💡 Note: All numbers in the matrix are non-negative, so the count is 0
Example 3 — Mixed Pattern
$ Input: grid = [[1,-1],[-1,-1]]
Output: 3
💡 Note: Row 1 has 1 negative (-1), Row 2 has 2 negatives (-1, -1). Total = 1 + 2 = 3

Constraints

  • m == grid.length
  • n == grid[i].length
  • 1 ≤ m, n ≤ 100
  • -100 ≤ grid[i][j] ≤ 100

Visualization

Tap to expand
Count Negative Numbers in Sorted Matrix INPUT m x n sorted matrix (non-increasing) 4 3 -1 -3 -4 -5 col 0 col 1 col 2 row 0 row 1 Positive/Zero Negative grid = [ [4, 3, -1], [-3, -4, -5]] Rows: 2, Cols: 3 Sorted: non-increasing Start: top-right corner ALGORITHM STEPS 1 Start Position Begin at top-right: (0, 2) Value = -1 (negative) 2 Check and Move If negative: count all below Move left (col--) 3 Continue Search If positive: move down Until out of bounds 4 Accumulate Count Add (m - row) each time negative found Staircase Path: 4 3 -1 -3 -4 -5 FINAL RESULT Execution Trace: pos(0,2): -1 neg +2 pos(0,1): 3 pos move down pos(1,1): -4 neg +1 pos(1,0): -3 neg +1 col = -1: done Count Breakdown Step 1: 2 negatives (col 2) Step 2: 1 negative (col 1) Step 3: 1 negative (col 0) Output: 4 4 negative numbers found Time: O(m+n) | Space: O(1) Key Insight: Staircase Search from Top-Right Starting from the top-right corner exploits the sorted property: moving LEFT increases values, moving DOWN decreases values. When we find a negative at (row, col), ALL elements below it in that column are also negative (m - row elements). This gives O(m+n) time complexity! TutorialsPoint - Count Negative Numbers in a Sorted Matrix | Staircase Search Approach
Asked in
Amazon 25 Microsoft 18 Google 15
28.5K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen