Skip to main content

Command Palette

Search for a command to run...

Solving Leetcode Interviews in Seconds with AI: Count Negative Numbers in a Sorted Matrix

Updated
2 min read

Introduction

In this blog post, we will explore how to solve the LeetCode problem "1351" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.

Problem Statement

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. Example 1: Input: grid = [[4,3,2,-1],[3,2,1,-1],[1,1,-1,-2],[-1,-1,-2,-3]] Output: 8 Explanation: There are 8 negatives number in the matrix. Example 2: Input: grid = [[3,2],[1,0]] Output: 0 Constraints: m == grid.length n == grid[i].length 1 <= m, n <= 100 -100 <= grid[i][j] <= 100 Follow up: Could you find an O(n + m) solution?

Explanation

Here's an efficient solution to count negative numbers in a row-wise and column-wise sorted matrix:

  • Leverage Sorted Order: Exploit the non-increasing order to efficiently find the first negative number in each row. Once a negative number is found in a row, all subsequent elements in that row are also negative.
  • Optimized Row Traversal: Start from the rightmost column of each row. Move leftwards until a non-negative number is encountered or the beginning of the row is reached. The remaining elements to the right are all negative.
  • Early Termination: The follow-up asks for O(n+m) time complexity. Start from the bottom-left of the matrix. If the value is negative, then everything above it is negative, so increment the count by remaining rows and move to the left. If the value is positive, then go up to the next row.

  • Runtime Complexity: O(m + n), where m is the number of rows and n is the number of columns. Storage Complexity: O(1) (constant).

Code

    def count_negatives(grid):
    """
    Counts the number of negative numbers in a row-wise and column-wise sorted matrix.

    Args:
        grid: A list of lists representing the matrix.

    Returns:
        The number of negative numbers in the matrix.
    """
    m = len(grid)
    n = len(grid[0])
    count = 0
    row = m - 1
    col = 0

    while row >= 0 and col < n:
        if grid[row][col] < 0:
            count += (m - row)
            col += 1
        else:
            row -= 1

    return count

More from this blog

C

Chatmagic blog

2894 posts