Skip to main content

Command Palette

Search for a command to run...

Solving Leetcode Interviews in Seconds with AI: Number of Submatrices That Sum to Target

Updated
2 min read

Introduction

In this blog post, we will explore how to solve the LeetCode problem "1074" 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 matrix and a target, return the number of non-empty submatrices that sum to target. A submatrix x1, y1, x2, y2 is the set of all cells matrix[x][y] with x1 <= x <= x2 and y1 <= y <= y2. Two submatrices (x1, y1, x2, y2) and (x1', y1', x2', y2') are different if they have some coordinate that is different: for example, if x1 != x1'. Example 1: Input: matrix = [[0,1,0],[1,1,1],[0,1,0]], target = 0 Output: 4 Explanation: The four 1x1 submatrices that only contain 0. Example 2: Input: matrix = [[1,-1],[-1,1]], target = 0 Output: 5 Explanation: The two 1x2 submatrices, plus the two 2x1 submatrices, plus the 2x2 submatrix. Example 3: Input: matrix = [[904]], target = 0 Output: 0 Constraints: 1 <= matrix.length <= 100 1 <= matrix[0].length <= 100 -1000 <= matrix[i][j] <= 1000 -10^8 <= target <= 10^8

Explanation

Here's the solution to the problem:

  • Prefix Sum: Calculate the prefix sum of the matrix to efficiently compute the sum of any submatrix in O(1) time.
  • Iterate and Check: Iterate through all possible pairs of columns (left, right). For each pair, calculate the sum of elements between these columns for each row.
  • Hash Map for Sum Counting: Use a hash map to count the occurrences of different row sums. For each row, update the sum and check if current_sum - target exists in the hash map. If it does, increment the count by the number of times that difference has occurred.

  • Time Complexity: O(cols^2 rows), *Space Complexity: O(rows)

Code

    def numSubmatrixSumTarget(matrix, target):
    rows = len(matrix)
    cols = len(matrix[0])
    count = 0

    # Iterate through all possible pairs of columns
    for left in range(cols):
        row_sums = [0] * rows  # Reset row sums for each left column

        for right in range(left, cols):
            # Update row sums for the current right column
            for i in range(rows):
                row_sums[i] += matrix[i][right]

            # Use a hash map to count submatrix sums
            sum_count = {0: 1}  # Initialize with 0:1 to handle submatrices starting from the first row
            curr_sum = 0

            for row_sum in row_sums:
                curr_sum += row_sum
                diff = curr_sum - target

                if diff in sum_count:
                    count += sum_count[diff]

                if curr_sum in sum_count:
                    sum_count[curr_sum] += 1
                else:
                    sum_count[curr_sum] = 1

    return count

More from this blog

C

Chatmagic blog

2894 posts