Problem 1074

Abstract / Summary

Count how many submatrices in a given matrix add up to a specified target value.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 1074.py

class Solution:
    def numSubmatrixSumTarget(self, matrix: List[List[int]], target: int) -> int:
        result = 0

        height = len(matrix)
        width  = len(matrix[0])

        # row-wise prefix sum (in situ)
        for m in matrix:
            for x in range(1, width):
                m[x] += m[x - 1]

        for left in range(width):
            for right in range(left, width):
                have = { 0: 1 } # properly catch rectangles starting in the first column

                prefix = 0 # vertical prefix sum
                for y in range(height):
                    # sliding window
                    prefix += matrix[y][right]
                    prefix -= matrix[y][left - 1] if left > 0 else 0

                    need         = prefix - target
                    result      += have.get(need,   0)
                    have[prefix] = have.get(prefix, 0) + 1

        return result
27 lines | 944 bytes | submitted May 6, 2024 | GitHub   21% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 75% (200k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Hash Table
  • Matrix
  • Prefix Sum
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The numSubmatrixSumTarget method counts how many sub-matrices of a given integer matrix have a sum equal to a specified target value. It first transforms each row into a running prefix sum, then iterates over all pairs of column boundaries. For each pair it collapses the two-dimensional problem into a one-dimensional prefix-sum problem along the rows, using a hash map to count how many previous vertical prefix sums would form a sub-matrix with the required total. The final count is accumulated in result and returned.

Key Steps

Row-wise Prefix Sum

Before any column pair is examined, each row is converted in-place to a prefix-sum representation. This allows the sum of any horizontal segment [left, right] in a row to be obtained with a single subtraction.

for m in matrix:
    for x in range(1, width):
        m[x] += m[x - 1]

The inner loop adds the value of the previous cell to the current cell, so after execution m[x] holds the sum of elements from column 0 through column x in that row.

Enumerating Column Pairs

The algorithm considers every possible left and right column index, inclusive, to define the horizontal span of a candidate sub-matrix. The outer loops generate these pairs:

for left in range(width):
    for right in range(left, width):
        have = {0: 1}
        prefix = 0
        # inner loop follows

left starts at the first column and right runs from left to the last column, guaranteeing that each distinct column interval is processed exactly once. The dictionary have is seeded with {0: 1} so that a vertical prefix that itself equals the target is counted as a valid rectangle beginning at the first column.

Accumulating Vertical Prefix and Counting Sub-matrices

For a fixed column pair, the algorithm walks down the rows, maintaining a running vertical prefix sum that represents the total of the rectangle bounded by the current row and the selected columns. The inner loop updates this prefix, adjusts for the left boundary, and uses the hash map to find how many earlier prefixes would complete a rectangle whose sum matches target.

for y in range(height):
    prefix += matrix[y][right]
    prefix -= matrix[y][left - 1] if left > 0 else 0

    need = prefix - target
    result += have.get(need, 0)
    have[prefix] = have.get(prefix, 0) + 1

prefix += matrix[y][right] adds the cumulative sum up to column right for the current row. If left is greater than zero, the contribution of columns left of the interval is subtracted using the previously computed row prefix. The variable need represents the prefix value that, when subtracted from the current prefix, yields the target sum. The dictionary lookup have.get(need, 0) yields the number of earlier rows that produced exactly that needed prefix, and this count is added to result. Finally, the current prefix is recorded in have for future rows.

Edge Cases Handled

When left equals zero the conditional subtraction matrix[y][left - 1] is bypassed, preventing an out-of-range access and correctly using the whole row prefix. The initialization have = {0: 1} ensures that a rectangle whose vertical prefix alone equals the target (i.e., a rectangle that starts at the first column) is counted. The in-place row prefix computation works for matrices with a single column because the inner loop over x simply does not execute, leaving each row unchanged but still valid for later subtraction logic. The algorithm also gracefully handles a matrix consisting of a single row; the outer column loops still generate all possible horizontal spans, and the inner vertical loop runs once, correctly counting any sub-array that meets the target.

Performance Optimizations

The row-wise prefix sums are computed in place, eliminating the need for an auxiliary matrix and reducing memory pressure. By collapsing the two-dimensional search into a series of one-dimensional prefix-sum problems, the code avoids recomputing sums for every possible rectangle; each vertical prefix is updated incrementally as the rows are traversed. The hash map have provides constant-time access to the count of previously seen prefixes, enabling immediate accumulation of matching sub-matrices without nested scans. Reinitializing have for each column pair rather than clearing a shared structure avoids unnecessary overhead while still reusing the same variable reference. The subtraction matrix[y][left - 1] is performed only when left is greater than zero, eliminating a redundant operation for the leftmost column. Together, these choices keep the core loops tight and memory-efficient while still exploring every valid rectangle.

written by openai gpt

ELI5 - Simplified Explanation

Imagine a large grid filled with numbers, like a floor made of square tiles each having a different amount of stickers on them. The goal is to figure out how many different secret rectangles can be hidden inside this grid so that all the stickers inside add up to one specific magic number.

First, the code goes through every single row and adds up the stickers horizontally. It turns each row into a running trail of totals. This makes it much easier to quickly grab the amount of stickers in any section of a row just by looking at the difference between two spots.

Next, the code starts searching for rectangles. It picks a starting left side and an ending right side to define the width. Then it slides a window from the top of the grid to the bottom. As it moves down, it keeps a running total of all the stickers found within that width.

To find the magic number, the code checks if it has seen a previous total that, when taken away from the current total, equals the target. It keeps a little notebook of every total it has seen so far so it can check these numbers instantly. Every time it finds a matching set, it counts it as one of the secret rectangles found. After looking at every possible combination of left, right, top, and bottom edges, the counting is finished.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 8 | μ = 8.00 | σ = 0.90

Complexity Analysis

Time: polynomial
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Python Java TS
WalkCCC C++ Python Java
leetcode.ca C++ Python Java Go TS
LeetcodeHelp C++ Python Java
Progiez C++ Python Java
github black-shadows C++
chandansgowda Python
charles-wangkai Java
everthis JS
fpdjsns C++
fsq C++
Garvit244 Python
halfrost Go
JoshCrozier JS
keineahnung2345 C++
lkwq007 Python
MacJim C++
suxrobGM C#
trung-hn Python
varunu28 Java
vthwang Java
wisdompeak C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, Python, TypeScript
LeetcodeHelp C++, Java, Python
Progiez C++, Java, Python
black-shadows C++, C++
chandansgowda Python
charles-wangkai Java
everthis JavaScript
fpdjsns C++
fsq C++
Garvit244 Python
halfrost Go
JoshCrozier JavaScript
keineahnung2345 C++
lkwq007 Python
MacJim C++
suxrobGM C#
trung-hn Python
varunu28 Java
vthwang Java
wisdompeak C++
35 links | 22 authors | 7 languages

Videos

8 videos   did my crawler come up with invalid videos ? drop me a line.

Solved On The Same Day

2 solutions   May 6, 2024

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality