#1351

Count Negative Numbers in a Sorted Matrix

Easy
ArrayBinary SearchMatrixTwo PointersMatrix Traversal
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(m * n)
O(n + m)
Space
O(1)
O(1)
💡

Intuition

Time O(n + m)Space O(1)

The optimal approach leverages the sorted nature of the matrix. Starting from the top-right corner, we can move left if the current number is negative (to find more negatives) or down if it's non-negative. This way, we can count negatives in O(n + m) time.

⚙️

Algorithm

6 steps
  1. 1Step 1: Initialize a counter to zero.
  2. 2Step 2: Start from the top-right corner of the matrix (row 0, column n-1).
  3. 3Step 3: While within bounds, check the current element:
  4. 4Step 4: If the element is negative, increment the counter and move left (column--).
  5. 5Step 5: If the element is non-negative, move down (row++).
  6. 6Step 6: Continue until you move out of bounds.
solution.py13 lines
1# Full working Python code
2
3def countNegatives(grid):
4    count = 0
5    m, n = len(grid), len(grid[0])
6    row, col = 0, n - 1
7    while row < m and col >= 0:
8        if grid[row][col] < 0:
9            count += (m - row)
10            col -= 1
11        else:
12            row += 1
13    return count

Complexity note: The time complexity is O(n + m) because in the worst case, we traverse either all rows or all columns. The space complexity is O(1) since we are using a constant amount of space for the counter and indices.

  • 1The matrix is sorted in non-increasing order, allowing for efficient traversal.
  • 2Counting negatives can be optimized by leveraging the sorted properties of the matrix.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.