Number of Submatrices That Sum to Target

Hard Arrays & Hashing Prefix Sum Strategy

Reported atSnapSamsung

Number of Submatrices That Sum to Target is a hard arrays & hashing problem solved with the prefix sum strategy pattern. The best approach, optimal (fix two rows, then subarray sum with a hash map), runs in O(m^2 * n) time and O(n) space. Below are 3 approaches in Java, Python, C++ and JavaScript, from brute force (add up every block) up.

Problem

You are given an m × n integer matrix matrix and an integer target.

A submatrix is any non-empty rectangular block of cells: it is chosen by a top row r1, a bottom row r2, a left column c1 and a right column c2 with r1 <= r2 and c1 <= c2, and it holds every cell matrix[i][j] with r1 <= i <= r2 and c1 <= j <= c2.

Return how many submatrices have cells that add up to exactly target. Two submatrices are counted separately when any of their four boundaries differ, even if they hold the same values.

The matrix may contain negative numbers.

Examples

Example 1

Input
matrix = [[1,-1,0],[0,1,-1]], target = 0
Output
8
Why
The eight blocks are: the 0 in row 0, the 0 in row 1, [1,-1] at the left of row 0, [1,-1] at the right of row 1, all of row 0, all of row 1, the middle column (-1 above 1), and the whole matrix.

Example 2

Input
matrix = [[2,1],[1,2]], target = 3
Output
4
Why
Each full row (2 + 1 and 1 + 2) and each full column (2 + 1 and 1 + 2) adds up to 3. Single cells and the whole matrix (6) do not.

Example 3

Input
matrix = [[5]], target = 4
Output
0
Why
The only block is the single cell, and it holds 5.

Constraints

  • 1 <= matrix.length <= 100
  • 1 <= matrix[0].length <= 100
  • -1000 <= matrix[i][j] <= 1000
  • -10^8 <= target <= 10^8

Solve it here

Write your solution in Java, Python, C++ or JavaScript and run it against the examples, right in the page. Submit runs the hidden tests too and, with a free account, records the solve in your revision log.

00:00
Testcase

Run checks the testcases above (3 examples, or your own). Submit also runs 15 hidden tests and saves the solve to your log. Signed in, every Run and Submit is saved under My submissions; your draft stays in this browser.

Animated walkthrough

A narrated, step-by-step animation that builds the solution from the idea up. Press play, or step through it at your own pace.

Concepts first, then the problem and every approach, step by step.

Space to play or pause · ← → to jump a step · click or drag the bar to seek

Solutions

Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the code in Java, Python, C++ and JavaScript.

ApproachTimeSpace
Brute force (add up every block)O(m^3 * n^3)O(1)
2D prefix sums (every block in O(1))O(m^2 * n^2)O(m * n)
Optimal (fix two rows, then subarray sum with a hash map)O(m^2 * n)O(n)

1Brute force (add up every block)

TimeO(m^3 * n^3)There are about m^2 n^2 / 4 blocks, and adding up one block can touch m × n cells.
SpaceO(1)Only a running sum and a counter.

Try every block: every top row, bottom row, left column and right column. Add up the cells inside it with two more loops and count the blocks whose sum equals target.

  1. For every top r1 and bottom r2 >= r1, and every left c1 and right c2 >= c1:
  2. Add up matrix[i][j] for i from r1 to r2 and j from c1 to c2.
  3. If the sum equals target, add one to the count. Return the count.
class Solution {
    public int numSubmatrixSumTarget(int[][] matrix, int target) {
        int m = matrix.length, n = matrix[0].length, count = 0;
        for (int r1 = 0; r1 < m; r1++) {
            for (int r2 = r1; r2 < m; r2++) {
                for (int c1 = 0; c1 < n; c1++) {
                    for (int c2 = c1; c2 < n; c2++) {
                        int sum = 0;
                        for (int i = r1; i <= r2; i++) {
                            for (int j = c1; j <= c2; j++) sum += matrix[i][j];
                        }
                        if (sum == target) count++;
                    }
                }
            }
        }
        return count;
    }
}

22D prefix sums (every block in O(1))

TimeO(m^2 * n^2)Building the table is O(mn), then every one of the O(m^2 n^2) blocks is checked in constant time.
SpaceO(m * n)The prefix table has (m + 1)(n + 1) entries.

Precompute pre[i][j], the sum of the top-left block with i rows and j columns. Any block's sum is then the big top-left block, minus the strip above it, minus the strip to its left, plus the corner that was taken away twice. Each of the m^2 n^2 / 4 blocks now costs four lookups instead of a full scan.

  1. pre is (m + 1) × (n + 1), with row 0 and column 0 all zero.
  2. pre[i + 1][j + 1] = matrix[i][j] + pre[i][j + 1] + pre[i + 1][j] - pre[i][j].
  3. For every block (r1, r2, c1, c2): sum = pre[r2 + 1][c2 + 1] - pre[r1][c2 + 1] - pre[r2 + 1][c1] + pre[r1][c1].
  4. Count the blocks whose sum equals target.
class Solution {
    public int numSubmatrixSumTarget(int[][] matrix, int target) {
        int m = matrix.length, n = matrix[0].length;
        // pre[i][j] = sum of the top-left block with i rows and j columns
        int[][] pre = new int[m + 1][n + 1];
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                pre[i + 1][j + 1] = matrix[i][j] + pre[i][j + 1] + pre[i + 1][j] - pre[i][j];
            }
        }
        int count = 0;
        for (int r1 = 0; r1 < m; r1++) {
            for (int r2 = r1; r2 < m; r2++) {
                for (int c1 = 0; c1 < n; c1++) {
                    for (int c2 = c1; c2 < n; c2++) {
                        int sum = pre[r2 + 1][c2 + 1] - pre[r1][c2 + 1] - pre[r2 + 1][c1] + pre[r1][c1];
                        if (sum == target) count++;
                    }
                }
            }
        }
        return count;
    }
}

3Optimal (fix two rows, then subarray sum with a hash map)

TimeO(m^2 * n)There are m(m + 1)/2 pairs of rows, and each pair does O(n) work to update colSum and scan it with the hash map. If m were much larger than n, swapping the roles of rows and columns would give O(n^2 * m).
SpaceO(n)colSum and the hash map each hold at most n + 1 entries.

Fix the top row and the bottom row of the block. Every block between them is a range of columns, and its sum is the sum of those columns' totals between the two rows. So squash the rows into one array colSum, where colSum[j] is column j added up from top to bottom. Counting blocks is now counting subarrays of colSum that add up to target: walk a running sum and, at each column, add how many earlier running sums equal running sum minus target. When the bottom row moves down by one, colSum just gains that row, so it is updated in O(n).

  1. For each top row: colSum is an array of n zeros.
  2. For each bottom row from top down: add matrix[bottom][j] to colSum[j] for every j.
  3. seen is a hash map with {0: 1} for the empty prefix; run = 0.
  4. For each j: run += colSum[j]; add seen[run - target] (0 if missing) to the count; then increase seen[run] by one.
  5. Return the count.
class Solution {
    public int numSubmatrixSumTarget(int[][] matrix, int target) {
        int m = matrix.length, n = matrix[0].length, count = 0;
        for (int top = 0; top < m; top++) {
            // colSum[j] = column j added up from row top to row bottom
            int[] colSum = new int[n];
            for (int bottom = top; bottom < m; bottom++) {
                for (int j = 0; j < n; j++) colSum[j] += matrix[bottom][j];
                // count the subarrays of colSum that add up to target
                Map<Integer, Integer> seen = new HashMap<>();
                seen.put(0, 1);
                int run = 0;
                for (int j = 0; j < n; j++) {
                    run += colSum[j];
                    count += seen.getOrDefault(run - target, 0);
                    seen.put(run, seen.getOrDefault(run, 0) + 1);
                }
            }
        }
        return count;
    }
}

Edge cases to test

  • A single cell: the answer is 1 if it equals target, otherwise 0
  • target = 0 with negative numbers: blocks can cancel out to zero in many ways
  • All zeros with target 0: every one of the m(m + 1)/2 × n(n + 1)/2 blocks counts
  • A target far larger than any possible sum: the answer is 0
  • A single row or a single column: the problem becomes counting subarrays with a given sum
  • Negative values mean sums do not grow as a block gets bigger, so a sliding window does not work

Hints

Hint 1

A block is fixed by its top row, bottom row, left column and right column. With a 2D prefix sum table, each block's sum takes four lookups.

Hint 2

Fix the top and bottom rows. Squash the rows between them into one array: entry j is the sum of column j over those rows. Now every block between those rows is a subarray of that array.

Hint 3

Counting subarrays of an array that add up to target is a classic: keep a running sum and a hash map of how often each earlier running sum appeared, and look up running sum minus target.

FAQ

What is the best time complexity for Number of Submatrices That Sum to Target?

Optimal (fix two rows, then subarray sum with a hash map) runs in O(m^2 * n) time and O(n) extra space. There are m(m + 1)/2 pairs of rows, and each pair does O(n) work to update colSum and scan it with the hash map. If m were much larger than n, swapping the roles of rows and columns would give O(n^2 * m).

Which pattern does Number of Submatrices That Sum to Target use?

It is a arrays & hashing problem that uses the prefix sum strategy pattern. Other problems with the same pattern: Subarray Sum Equals K, Subarray with given XOR, Range Sum Query - Immutable.

Is there a brute force solution for Number of Submatrices That Sum to Target?

Yes. Brute force (add up every block) takes O(m^3 * n^3) time and O(1) space. Try every block: every top row, bottom row, left column and right column.

Which edge cases should I test for Number of Submatrices That Sum to Target?

A single cell: the answer is 1 if it equals target, otherwise 0; target = 0 with negative numbers: blocks can cancel out to zero in many ways; All zeros with target 0: every one of the m(m + 1)/2 × n(n + 1)/2 blocks counts; A target far larger than any possible sum: the answer is 0; A single row or a single column: the problem becomes counting subarrays with a given sum; Negative values mean sums do not grow as a block gets bigger, so a sliding window does not work.