Count Negative Numbers in a Column-Wise and Row-Wise Sorted Matrix using Python?

In this example, we will count negative numbers in a column-wise and row-wise sorted matrix. A sorted matrix has elements arranged in ascending order both horizontally (across rows) and vertically (down columns).

Understanding the Problem

For a sorted matrix, once we encounter a positive number in a row, all subsequent elements in that row will also be positive. This property allows us to optimize our counting approach.

Creating the Matrix

Let's start by creating a sample sorted matrix ?

matrix = [
    [-7, -3, 2, 3],
    [-4, -1, 1, 6],
    [-2,  1, 2, 7]
]

print("Matrix:")
for row in matrix:
    print(row)
Matrix:
[-7, -3, 2, 3]
[-4, -1, 1, 6]
[-2, 1, 2, 7]

Method 1: Brute Force Approach

This method checks every element in the matrix ?

def count_negatives_brute_force(matrix):
    count = 0
    rows, cols = len(matrix), len(matrix[0])
    
    for i in range(rows):
        for j in range(cols):
            if matrix[i][j] < 0:
                count += 1
    
    return count

# Test the function
matrix = [
    [-7, -3, 2, 3],
    [-4, -1, 1, 6],
    [-2,  1, 2, 7]
]

result = count_negatives_brute_force(matrix)
print(f"Count of negative numbers: {result}")
Count of negative numbers: 5

Method 2: Optimized Row-wise Approach

Since the matrix is sorted, we can break early when we find the first positive number in each row ?

def count_negatives_optimized(matrix):
    count = 0
    
    for row in matrix:
        for element in row:
            if element < 0:
                count += 1
            else:
                # Since row is sorted, remaining elements are positive
                break
    
    return count

# Test the function
matrix = [
    [-7, -3, 2, 3],
    [-4, -1, 1, 6],
    [-2,  1, 2, 7]
]

result = count_negatives_optimized(matrix)
print(f"Count of negative numbers: {result}")
Count of negative numbers: 5

Method 3: Binary Search Approach

For each row, use binary search to find the first positive element ?

def count_negatives_binary_search(matrix):
    def find_negatives_in_row(row):
        left, right = 0, len(row) - 1
        
        while left <= right:
            mid = (left + right) // 2
            if row[mid] < 0:
                left = mid + 1
            else:
                right = mid - 1
        
        return left  # Number of negative elements
    
    total_count = 0
    for row in matrix:
        total_count += find_negatives_in_row(row)
    
    return total_count

# Test the function
matrix = [
    [-7, -3, 2, 3],
    [-4, -1, 1, 6],
    [-2,  1, 2, 7]
]

result = count_negatives_binary_search(matrix)
print(f"Count of negative numbers: {result}")
Count of negative numbers: 5

Comparison

Method Time Complexity Space Complexity Best For
Brute Force O(m × n) O(1) Small matrices
Row-wise Early Break O(m × k) where k is avg negatives per row O(1) General case
Binary Search O(m × log n) O(1) Large matrices with few negatives

Complete Example

Here's a complete example comparing all three approaches ?

def count_negatives_optimized(matrix):
    count = 0
    for row in matrix:
        for element in row:
            if element < 0:
                count += 1
            else:
                break
    return count

# Test with different matrices
test_matrices = [
    [[-7, -3, 2, 3], [-4, -1, 1, 6], [-2, 1, 2, 7]],
    [[-5, -4, -3], [-2, -1, 0], [1, 2, 3]],
    [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
]

for i, matrix in enumerate(test_matrices, 1):
    print(f"Matrix {i}:")
    for row in matrix:
        print(row)
    
    result = count_negatives_optimized(matrix)
    print(f"Negative count: {result}\n")
Matrix 1:
[-7, -3, 2, 3]
[-4, -1, 1, 6]
[-2, 1, 2, 7]
Negative count: 5

Matrix 2:
[-5, -4, -3]
[-2, -1, 0]
[1, 2, 3]
Negative count: 5

Matrix 3:
[1, 2, 3]
[4, 5, 6]
[7, 8, 9]
Negative count: 0

Conclusion

For counting negative numbers in sorted matrices, the row-wise early break approach provides the best balance of simplicity and efficiency. Use binary search for very large matrices where most elements are positive.

---
Updated on: 2026-03-25T05:50:43+05:30

618 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements