HardArrayHash TableMatrixPrefix Sum

Number of Submatrices That Sum to Target

1 approach, code in every language

Problem description

You are given an m x n integer matrix and an integer target. Return the number of non-empty submatrices whose elements add up to exactly target.

A submatrix is defined by a contiguous range of rows (x1 to x2) and a contiguous range of columns (y1 to y2), and it includes every cell whose row is in [x1, x2] and column is in [y1, y2]. Two submatrices are counted as different if they differ in any of these four boundary indices, even if their contents are identical.

Example 1

Input: matrix = [[0,1,0],[1,1,1],[0,1,0]], target = 0

Output: 4

There are four submatrices that sum to 0, each consisting of a single 0 cell at the four corners of the matrix.

Example 2

Input: matrix = [[1,-1],[-1,1]], target = 0

Output: 5

Five distinct submatrices sum to 0, including the full matrix and the four 1x2 or 2x1 bands that pair a 1 with a -1.

Constraints

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

After the pattern

Now solve one you haven't seen.

Reading a pattern isn't the same as using it. The practice set has 1,194 original problems on the same techniques, each graded in your browser.

1,194 problems · 15,062 graded tests · free