Count Negative Numbers in a Sorted Matrix

You are given an `m x n` matrix `grid` whose rows and columns are both sorted in non-increasing order. Return how many of its numbers are negative.

30:00

Count Negative Numbers in a Sorted Matrix
easy
Free written solution
Topics
Companies

You are given an m x n matrix grid whose rows and columns are both sorted in non-increasing order. Return how many of its numbers are negative.

Example 1:
Input: {"grid":[[4,3,2,-1],[3,2,1,-1],[1,1,-1,-2],[-1,-1,-2,-3]]}
Output: 8
Constraints:
  • m==grid.lengthm == \text{grid.length}

  • n==grid[i].lengthn == \text{grid}[i].\text{length}

  • 1≤m,n≤1001 \leq m, n \leq 100

  • −100≤grid[i][j]≤100-100 \leq \text{grid}[i][j] \leq 100

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"grid":[[4,3,2,-1],[3,2,1,-1],[1,1,-1,-2],[-1,-1,-2,-3]]}

Start at the bottom-left corner (row 3, col 0). Moving up makes values bigger and moving right makes them smaller, so each look rules out a whole row or column.

staircase walk from the bottom-left corner

c

1

2

3

0

4
3
2
-1

+0

1

3
2
1
-1

+0

2

1
1
-1
-2

+0

r→

-1
-1
-2
-3

+0

pointer (r, c)

counted negative

ruled out (>= 0)

pointer

(3, 0) = -1

count

0

Variables
VariableValue
r3
c0
count0
DepthFunction Call
Stack empty
0/15